What is the difference between these two Ruby snippets?

Fragment 1:

module A
  def cm(m,ret)
    class_eval do
     define_method(m.to_sym) do
       return ret
     end
    end
  end
end

and fragment 2:

module B
  def cm(m,ret)
    class_eval do
      "def #{m} #{ret} end"
    end
  end
end

The methods defined in these modules should be used to create methods of the class that returns specific values. Here is an example:

class Whatever
  extend A
  cm("two",2)
end

and this will create a method called 2, which will return 2. The fact is that the code in the second fragment does not work. Any ideas why? I thought I class_evalcould take a string.

+3
source share
1 answer

class_eval takes a string as an argument, but you 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
+5
source

Source: https://habr.com/ru/post/1729871/


All Articles