eval

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}" )        #=> 3

Sometimes, 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*4

Let’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}" ...

Get The Book of Ruby now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.