Question

I have a strange situation where the code:

c = Class.new { eval parser }

... works in IRB (ruby 1.9.3) but not in code. I've tried it with and without 'class Foo' wrapping my methods. This is frustrating, to say the least. I can copy the string parser's content directly into variable parser in irb, and then create the class using the above line and my methods are all there but when I do it in code, they aren't.

Was it helpful?

Solution 2

I've solved it.

The situation was that I was dynamically creating the definitions in order to make an optimized parser, and I was building it using incrementally added strings. As you can imagine, there was a lot of quote-escaping involved, especially with the MySQL queries. When I tested in irb, I forgot that using

puts parser

... evaluated the string while printing, removing one level of escaping while doing so.

The solution was simple: eval my string before class_eval'ing it.

fetchclass = Object.const_set(
                characteristics['shortname'],
                Class.new { class_eval( eval parser ) } )

OTHER TIPS

C = Class.new
C.class_eval(code)

...Works for me in Ruby 1.9.2, even when saved in a file. Can you try and see if it works in 1.9.3?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top