Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a ruby Proc from a string

Tags:

ruby

lambda

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
like image 387
fjs6 Avatar asked Mar 17 '10 00:03

fjs6


2 Answers

This works

eval  "lambda { " + code_string + " }"

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

like image 190
fjs6 Avatar answered Sep 23 '22 00:09

fjs6


eval "lambda {#{code_string}}"

like image 23
Weston Ganger Avatar answered Sep 24 '22 00:09

Weston Ganger