Created
March 6, 2013 11:50
-
-
Save lgmkr/5098799 to your computer and use it in GitHub Desktop.
Method Chaining for instance and class
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 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