11

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
3
  • 1
    I don't mean to sound rude, but why in the world do you want to do this? eval is almost never the best way to do something, for efficiency's sake if nothing else. Commented Mar 17, 2010 at 2:35
  • This definitely seems pretty hacky Commented Mar 17, 2010 at 3:36
  • Sometimes you need to generate code "on-the-fly", often from a source that is not Ruby code. I use this technique to implement a transpiler. Commented Dec 6, 2016 at 18:18

2 Answers 2

10

This works

eval  "lambda { " + code_string + " }"

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

Sign up to request clarification or add additional context in comments.

2 Comments

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

eval "lambda {#{code_string}}"

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.