开发者

Compile a string to Ruby bytecode for better performance -- like compile() in Python

开发者 https://www.devze.com 2022-12-14 10:46 出处:网络
I have a string (authenticated, trusted, etc.) containing source code intended to run within a Ruby loop, quickly.In Python, I would compile the string into an abstract syntax tree and 开发者_JAVA百科

I have a string (authenticated, trusted, etc.) containing source code intended to run within a Ruby loop, quickly. In Python, I would compile the string into an abstract syntax tree and 开发者_JAVA百科eval() or exec() it later:

# 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]

Ruby does not have a compile function, so what is the best way to achieve this?


Based on the solution of jhs, but directly using the lambda as the loop body (the & calls to_proc on the lambda and passes it as block to the select function).

given_code = 'n % 2 == 1'
pred = eval "lambda { |n| #{given_code} }"
p all = (1..10).select(&pred)


I wrap the whole string in a lambda (still as a string), eval that, and then call the resultant Proc object.

# XXX: Only runs on Ruby 1.8.7 and up.
given_code = 'n % 2 == 1'
pred = eval "lambda { |n| #{given_code} }"
puts 1.upto(10).select { |x| pred.call(x) } .inspect # Or (1..10).select for Ruby <= 1.8.6
# Output: [1, 3, 5, 7, 9]
0

精彩评论

暂无评论...
验证码 换一张
取 消