Rubén Medellín
10/20/2006 6:36:00 PM
Jan Svitok wrote:
> Sometimes (=rarely), when you want to require later or not at all,
> it's useful to put require inside a method.
Just to make it a little clearer, by experimenting you can see:
-------------
def check
a = ['foo', 'bar', 'baz'] * 2
begin
a.each_slice(3) {|slice| p slice}
rescue Exception
puts "No such method\n"
end
require 'enumerator'
a.each_slice(3){|slice| p slice}
end
#Test starts here
begin
x.each_slice(3) {|slice| p slice}
rescue Exception
puts "No such method\n"
end
puts $".include?('enumerator.so')
check
puts $".include?('enumerator.so')
x = ['foo', 'bar', 'baz'] * 2
x.each_slice(2) {|slice| p slice}
---------------
Produces ->
No such method
false
No such method
["foo", "bar", "baz"]
["foo", "bar", "baz"]
true
["FOO", "BAR"]
["BAZ", "FOO"]
["BAR", "BAZ"]
As you can see, 'require' is itself a method (btw, mixed with the
require method of rubygems/custom_require.rb if specified), that calls
a library and adds it to $". Such library is called the first time is
required. So, as Jan said, you may call it anywhere on your program
depending on where do YOU require it.