Skip to content

Instantly share code, notes, and snippets.

@theHamdiz
Last active April 17, 2018 15:33
Show Gist options
  • Save theHamdiz/369896b99d8bf2a5d37b to your computer and use it in GitHub Desktop.
Save theHamdiz/369896b99d8bf2a5d37b to your computer and use it in GitHub Desktop.
Learn how to build flexible interfaces using instance_eval in #ruby
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