views:

66

answers:

1

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.

+5  A: 

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
liwp
I still think the definition itself looks wrong. wouldn't it be : "def #{m}; return #{ret}; end"
Jean
@Jean: The return keyword is optional when the expression is the last one in the method anyway. So is a terminator before the end keyword or after the argument list of a method defintion. I.e. `def five() 5 end` is valid syntax. However `def five 5 end` is not.
sepp2k