Jas*_*ith 4 ruby python eval compilation
我有一个字符串(经过身份验证,可信任等),其中包含旨在快速在Ruby循环中运行的源代码.在Python中,我会将字符串编译成抽象语法树,eval()或者exec()稍后编译:
# Python 3 example
given_code = 'n % 2 == 1'
pred = compile(given_code, '<given>', 'eval')
print("Passed:", [n for n in range(10) if eval(pred)])
# Outputs: Passing members: [1, 3, 5, 7, 9]
Run Code Online (Sandbox Code Playgroud)
Ruby没有编译功能,那么实现这一目标的最佳方法是什么?
基于jhs的解决方案,但直接使用lambda作为循环体(对lambda 的&调用to_proc并将其作为块传递给select函数).
given_code = 'n % 2 == 1'
pred = eval "lambda { |n| #{given_code} }"
p all = (1..10).select(&pred)
Run Code Online (Sandbox Code Playgroud)