Geo
Geo

Reputation: 96827

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 used 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.

Upvotes: 3

Views: 125

Answers (1)

liwp
liwp

Reputation: 6926

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

Upvotes: 5

Related Questions