What's the difference between these two Ruby snippets?
Snippet 1:
module A
def cm(m,ret)
class_eval do
define_method(m.to_sym) do
return ret
end
end
end
end
and snippet 2:
module B
def cm(m,ret)
class_eval do
"def #{m} #{ret} end"
end
end
end
The methods defined in these modules are to be use开发者_C百科d to create methods on a class, that returns certain values. Here's an example:
class Whatever
extend A
cm("two",2)
end
and this will create a method named 2, that will return 2. The thing is, the code in the second snippet does not work. Any ideas why? I thought class_eval
could take a string.
class_eval
takes a string as an argument, but you've passed the string to the function in a block.
Try this instead:
module B
def cm(m,ret)
class_eval("def #{m}() #{ret} end")
end
end
精彩评论