[Ruby] What happens if the method self is used as the return value?

You will be able to connect again and use the same method.

Practical example

class Hoge
  def foo
     self
  end
end

Hoge.new.foo
#<Hoge:0x00007f92612b2e38>

Hoge.new.foo.foo.foo.foo
#<Hoge:0x00007f92618c82a0>

In this way, since the return value is the same type, it is possible to use the same method again.

Commentary

a.method b

In this situation, the return value will be the receiver a. So

c = a.method b

Then, the same type as a is output to c.

Application example

Hold the instance variable and count the number of times the method is called.

class Hoge
  def foo
     @a.nil? ? @a = 1 : @a = @a + 1 
     self
  end
end

Hoge.new.foo
=> #<Hoge:0x00007f92618c2080 @a=1>

Hoge.new.foo.foo.foo.foo
=> #<Hoge:0x00007f92618a0a98 @a=4>

Then you can see that the value of @a is incremented by the number of times the foo method is called.

Recommended Posts

[Ruby] What happens if the method self is used as the return value?
What is the pluck method?
[Ruby] What is `!!` used for?
What is the initialize method?
What is the main method in Java?
Ruby methods return the last evaluated value
[Java] You might be happy if the return value of a method that returns null is Optional <>
If it is Ruby, it is efficient to make it a method and stock the processing.
What is self
[Ruby] What is the slice method? Let's solve the example and understand the difference from slice!
Pass arguments to the method and receive the result of the operation as a return value
What is Ruby's self?
[Ruby] What is true?
Determine that the value is a multiple of 〇 in Ruby
What is the difference between an action and an instance method?
9 Corresponds to the return value
What is a Ruby module?
What is the BufferedReader class?
[Ruby] What is an instance?
What is the constructor for?
[Ubuntu 20.04] What to do if the external monitor is not recognized
Want to know what Ruby n is the power of 2? (Power judgment of 2)
What to do if Cloud9 is full in the Rails tutorial
What to do if the Eclipse Maven dependency Jar is wrong