July 2011
Intermediate to advanced
400 pages
8h 46m
English
The eval method provides a simple way of evaluating a Ruby expression in a string. At first sight, eval may appear to do the same job as the #{ } delimiters in a double-quoted string. These two lines of code produce identical results:
eval.rb
puts( eval("1 + 2" ) ) #=> 3
puts( "#{1 + 2}" ) #=> 3Sometimes, however, the results may not be what you are expecting. Look at the following, for instance:
eval_string.rb
exp = gets().chomp() #<= User enters 2*4
puts( eval( exp )) #=> 8
puts( "#{exp}" ) #=> 2*4Let’s suppose you enter 2 * 4, and this is assigned to exp. When you evaluate exp with eval, the result is 8, but when you evaluate exp in a double-quoted string, the result is "2*4". This is because anything read in by gets() is a string and "#{exp}" ...
Read now
Unlock full access