Last active
April 17, 2018 15:33
-
-
Save theHamdiz/369896b99d8bf2a5d37b to your computer and use it in GitHub Desktop.
Learn how to build flexible interfaces using instance_eval 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 Person | |
def name(n) | |
@name = n | |
self | |
end | |
def age(a) | |
@age = a | |
self | |
end | |
def to_s | |
"Hi there I am #{@name} and I am #{@age} years old!" | |
end | |
class << self | |
def people | |
@@people ||= [] | |
end | |
def add(&block) | |
people << new.instance_eval(&block) | |
end | |
end | |
end | |
person = Person.add { name 'Ahmad Hamdi'; age 22 } | |
puts person # => Hi there I am Ahmad Hamdi and I am 22 years old! | |
another = Person.add { name 'Ashraf'; age 55 } | |
puts another # => Hi there I am Ashraf and I am 55 years old! | |
p Person.people |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment