Tuesday, October 5, 2010

Ruby create a class object with name determined at runtime, calling dynamic methods

http://ruby-doc.org/docs/ProgrammingRuby/html/ospace.html

Calling a method unknown during compile time.

So we want to call a method but we only get the method's name at runtime, use the 'send' method
ruby-1.8.7-p302 > 'John Coltran'.send('length')
 => 12


or using 'method' to call it later

or 'eval'

r = eval "'John Coltran'.length"
 => 12

-------------------------------------

http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/190828

$ irb
ruby-1.8.7-p302 > b=Object::const_get('String').new()
 => ""
ruby-1.8.7-p302 > b
 => ""
ruby-1.8.7-p302 > b.class
 => String

# Print all User tuples
>  b = Object::const_get('User').new()
>  puts b.class
 => String
>  puts b.class.all
#


$ rails console < my_script_helper.rb


--------class----------------
# The Greeter class
class Greeter
  def initialize(name)
    @name = name.capitalize
  end
  def salute
    puts "Hello #{@name}!"
  end
end
# Create a new object
g = Greeter.new("world")
# Output "Hello World!"
g.salute
vs
--------module-------------
http://ruby-doc.org/core/classes/Module.html
 A Module is a collection of methods and constants.

module Mod
     alias_method :orig_exit, :exit
     def exit(code=0)
       puts "Exiting with code #{code}"
       orig_exit(code)
     end
   end
   include Mod
   exit(99)

No comments: