Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 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?

like image 520
JasonSmith Avatar asked Feb 27 '23 22:02

JasonSmith


2 Answers

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)
like image 168
akuhn Avatar answered Apr 07 '23 00:04

akuhn


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]
like image 20
JasonSmith Avatar answered Apr 06 '23 22:04

JasonSmith