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?