SEARCH
0-9 A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
Prev | Current Page 431 | Next

Ola Bini

"Practical JRuby on Rails Web 2.0 Projects: Bringing Ruby on Rails to Java"

However, in most
cases you don??™t need that; it??™s usually enough to use either instance_eval or
module_eval/class_eval. eval takes a String containing the code to execute, while
instance_eval and module_eval take a block. That block will be executed in a different context
depending on which you use. If you run instance_eval, you can access instance_variables
and private methods of the instance executing within. If you use module_eval or class_eval,
you can define new methods using the def syntax.
1.instance_eval do
puts self
@foo = 42
end
String.module_eval do
def hello_world
end
end
As a last shot, you can always use eval:
ret = eval("1 + 42")
You can define new methods and classes based on strings:
method_name = 'do_it'
eval("def #{method_name}; puts 'hello'; end")
do_it
APPENDIX A ?–  RUBY FOR JAVA PROGRAMMERS 304
The Symbol to_proc Trick
A useful trick is extensively used in much of the Rails code, based on what happens when you
use & to turn a Proc instance into a block to a method call. I??™ll show it to you in a bit, but first
look at this:
a = ["one", "two", 1..3]
p a.map { |arg| arg.inspect }
This prints
["one", "two", 1..3]
That??™s because the map method call returns an array containing the result of running the
provided block on each value of itself. Now, it??™s common to call a method with no arguments
when using a block. The Symbol to_proc trick makes it possible to write the preceding code
like this instead:
a = ["one", "two", 1.


Pages:
419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443