Skip to content

Instantly share code, notes, and snippets.

@metaskills
Created May 19, 2010 20:55
Show Gist options
  • Save metaskills/406827 to your computer and use it in GitHub Desktop.
Save metaskills/406827 to your computer and use it in GitHub Desktop.
class Animal < Struct.new(:species)
end
o1 = Animal.new(:duck)
o2 = Animal.new(:duck)
o3 = Animal.new(:goose)
[o1,o2,o3].each do |animal|
sound = animal.species == :duck ? 'Quack' : 'Say What?'
animal.instance_variable_set :@sound, sound
def animal.speak ; instance_variable_get(:@sound) ; end
end
o1.speak # => "Quack"
o2.speak # => "Quack"
o3.speak # => "Say What?"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment