Skip to content

Instantly share code, notes, and snippets.

@slant
Created May 22, 2015 21:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save slant/0c3df6054705f28fa0fb to your computer and use it in GitHub Desktop.
Save slant/0c3df6054705f28fa0fb to your computer and use it in GitHub Desktop.
Chaining methods in Ruby
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