Skip to content

Instantly share code, notes, and snippets.

@lgmkr
Created March 6, 2013 11:50
Show Gist options
  • Save lgmkr/5098799 to your computer and use it in GitHub Desktop.
Save lgmkr/5098799 to your computer and use it in GitHub Desktop.
Method Chaining for instance and class
class Person
def name(value)
@name = value
self
end
def age(value)
@age = value
self
end
def introduce
puts "Hello, my name is #{@name} and I am #{@age} years old."
end
end
> person = Person.new
# => #<Person:0x007ff202829e38>
> person.name('Baz')
# => #<Person:0x007ff202829e38 @name="Baz">
> person.name('Baz').age(21)
# => #<Person:0x007ff202829e38 @name="Baz", @age=21>
class Speaker
class << self
def say(what)
@say = what
self
end
def drink(what)
@drink = what
self
end
def output
"The speaker drinks #{@drink} and says #{@say}"
end
end
end
> Speaker.say('hello').drink('water').output
# => The speaker drinks water and says hello
module SpeakerClassMethods
def say(what)
@say = what
self
end
def drink(what)
@drink = what
self
end
def output
"The speaker drinks #{@drink} and says #{@say}"
end
end
class Speaker
extend SpeakerClassMethods
end
> Speaker.say('hello').drink('water').output
# => The speaker drinks water and says hello
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment