class Hash
def to_method
hash = self
Module.new do
hash.each_pair do |k,v|
define_method k.to_sym do
v
end
end
end
end
end
class Test
def initialize(hash)
self.extend hash.to_method
end
end
k = Test.new(:fun1 => 'var1')
p k.fun1
这段代码没有问题~
class Hash
def to_method
hash = self
Module.new do
hash.each_pair do |k,v|
define_method k.to_sym { v } # 就见过这里的do end, 改成了 {}
end
end
end
end
class Test
def initialize(hash)
self.extend hash.to_method
end
end
k = Test.new(:fun1 => 'var1')
p k.fun1
报错
define_hash_method.v2.rb:6:in `define_method': tried to create Proc object without a block (ArgumentError)
from define_hash_method.v2.rb:6:in `block (2 levels) in to_method'
from define_hash_method.v2.rb:5:in `each_pair'
from define_hash_method.v2.rb:5:in `block in to_method'
from define_hash_method.v2.rb:4:in `initialize'
from define_hash_method.v2.rb:4:in `new'
from define_hash_method.v2.rb:4:in `to_method'
from define_hash_method.v2.rb:14:in `initialize'
from define_hash_method.v2.rb:18:in `new'
from define_hash_method.v2.rb:18:in `<main>'