开发者

What's the difference between these two Ruby snippets?

开发者 https://www.devze.com 2022-12-17 20:27 出处:网络
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:

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
0

精彩评论

暂无评论...
验证码 换一张
取 消