Skip to content

Instantly share code, notes, and snippets.

@louis-wu
Created January 28, 2010 09:21
Show Gist options
  • Save louis-wu/288575 to your computer and use it in GitHub Desktop.
Save louis-wu/288575 to your computer and use it in GitHub Desktop.
metaprogramming
#Struct allows you to define classes that contain just data attributes.
Person = Struct.new(:name, :address, :likes)
dave = Person.new('Dave', 'TX')
dave.likes = "Programming Languages"
puts dave
# opening up the class and writing the method
Person = Struct.new(:name, :address, :likes)
class Person
def to_s
"#{self.name} lives in #{self.address} and likes #{self.likes}"
end
end
# < 的右侧可以是个class名称,也可以是返回class对象的表达式。
class Person < Struct.new(:name, :address, :likes)
def to_s
"#{self.name} lives in #{self.address} and likes #{self.likes}"
end
end
dave = Person.new('Dave', 'Texas')
dave.likes = "Programming Languages"
puts dave
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment