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
#
# 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
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:
Post a Comment