class Demo
def initialize(n)
@iv = n
end
def hello()
"Hello, @iv = #{@iv}"
end
end
k = Demo.new(99)
m = k.method(:hello)
m.call #=> "Hello, @iv = 99"
l = Demo.new('Fred')
m = l.method("hello")
m.call #=> "Hello, @iv = Fred"
def square(x); x*x; end puts (1..10).map(&method(:square))
| El método define_method
de Module
espera un símbolo como argumento y crea un método con ese
nombre utilizando el bloque asociado como cuerpo del método.
Es posible también pasar a define_method un Proc o un Method en vez del bloque como segundo argumento.
$ cat define_method.rb
class Chazam
def initialize(data)
@data = data
end
%w(user email food).each do |meth|
define_method(meth) { @data[meth.to_sym] }
end
end
p = Chazam.new(:user => 'Juan', :food => 'Cucumber')
puts p.user
puts p.food
$ ruby define_method.rb Juan Cucumber |
Returns the name of the method.
Returns the class or module that defines the method.
Returns the parameter information of this method.
Returns the bound receiver of the method object.
Returns the Ruby source filename and line number containing this method or nil if this method was not defined in Ruby (i.e. native)