Skip to content

Instantly share code, notes, and snippets.

@codemilan
Forked from theHamdiz/flexible interface.rb
Created May 13, 2016 15:58
Show Gist options
  • Save codemilan/68dc08320638651f5c924db3a859e8a8 to your computer and use it in GitHub Desktop.
Save codemilan/68dc08320638651f5c924db3a859e8a8 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