tags:

views:

60

answers:

1

I want to define the block as a string, then create the lambda. The following example does not work. Is something like this possible?

code_string = "|x|x*2"

l = lambda {eval(code_string)}

l.call(3) => 6
+1  A: 

This works

eval  "lambda { " + code_string + " }"

I just don't know why this one does and the other does not.

fjs6
Calling lambda on an eval argument results in a Proc object with the eval call 'inside' the Proc object. The resulting Proc object doesn't take an argument, as the expression `eval(code_string)` doesn't take an argument. When you call the Proc object, it evals the code_string!The eval of the string "lambda { " + code_string + " }" gives a Proc object that is expecting an argument, and returns 2*argument.
Fred
Also, it's more idiomatic (and more efficient to boot) to use string interpolation, so it would be: `eval "lambda {#{code_string}}"`. Concatenating several strings with `+` is rarely done in Ruby.
Chuck