Created
May 22, 2015 21:08
-
-
Save slant/0c3df6054705f28fa0fb to your computer and use it in GitHub Desktop.
Chaining methods in Ruby
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Something | |
attr_accessor :thing | |
def initialize | |
self.thing = [] | |
end | |
def one | |
# by returning self on the last line of a method, that method will then | |
# allow another method to be called immediately after it since the next | |
# method will be called on `self`. | |
self.thing << 'first' | |
self | |
end | |
def two word='nothing' | |
# another way to do this is to include returning self on the same line. | |
# we're also now allowing the user to pass a variable as part of the chain. | |
(self.thing << word) && self | |
end | |
end | |
# these methods can now be chained | |
s1 = Something.new | |
puts s1.one.two.thing.inspect | |
#=> ["first", "nothing"] | |
# passing a variable | |
s2 = Something.new | |
puts s2.one.two('second').thing.inspect | |
#=> ["first", "second"] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment