[ next ] [ prev ] [ contents ] Invitation To Ruby

MetaClass Example

  1: #!/usr/bin/env ruby
  2: 
  3: class Dog
  4:   def talk() puts "Woof" end
  5: end
  6:   
  7: class Cat
  8:   def talk() puts "Meow" end
  9: end
 10:   
 11: animals = { 'dog'=>Dog, 'cat'=>Cat }
 12: 
 13: print "What kind of pet do you want? "
 14: pet_name = gets
 15: pet = animals[pet_name.chomp].new
 16: pet.talk

Output

$ ruby src/metaclass.rb
What kind of pet do you want? dog
Woof
$
$ ruby src/metaclass.rb
What kind of pet do you want? cat
Meow



[ next ] [ prev ] [ contents ] Copyright 2002 by Jim Weirich.
All rights reserved.