O'Reilly logo

Metaprogramming Ruby 2 by Paolo Perrotta

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Kernel#eval

Where you learn that, when it comes right down to it, code is just text.

You already learned about instance_eval and class_eval (in instance_eval(), and class_eval(), respectively). Now you can get acquainted with the third member of the *eval family—a Kernel Method (Kernel Method) that’s simply named eval. Kernel#eval is the most straightforward of the three *eval methods. Instead of a block, it takes a string that contains Ruby code—a Spell: String of Code for short. Kernel#eval executes the code in the string and returns the result:

ctwc/simple_eval.rb
 
array = [10, 20]
 
element = 30
 
eval(​"array << element"​) ​# => [10, 20, 30]

Executing a literal string of Ruby code is a pretty pointless exercise, but the power of ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required