Code is data, data is code
It is important for one to think of code as data to understand what
eval is all about. The idea is that the code itself can be manifested as a primitive data type which the language can then make sense of.
The data here is the string that is being passed through, the code being the Ruby expression that evaluates to 42.
This is similar to doing a normal multiplication operation.
eval. In the example below, we re-define the method
zento return 42 instead of 41.
evalthat returns a value that is greater than that stored in
answer. Make sure that the expression below becomes
evaltakes in a string as the argument, which means that it is possible for one to accept user input or read code off of a file and get it evaluated from within your program - essentially re-programming the way your program behaves.
This of course means that any changes you need to make with the code you've read from the file have to be done by the use of Ruby's string manipulation methods.
This is unlike many functional programming languages where code itself is a first-class data type (known as homoiconicity) and you can eval code by just passing in code.
evalis considered evil.
evalalso reduces the effectiveness of static code analysis tools, because our code is just masquerading as code, and is essentially just data.
rm -rfour root directory fails.
evalshould best be avoided in real scenarios. Ruby has saner tools (
#send) in its meta-programming repertoire that you can use to achieve eval-like cleverness.