This code comes from the online code examples for
the Programming Ruby book
#==== code start ========
module Inject
def inject(n)
each do |value|
n = yield(n, value)
end
n
end
def sum(initial = 0)
inject(initial) { |n, value| n + value }
end
def product(initial = 1)
inject(initial) { |n, value| n * value }
end
end
class Array
include Inject
end
class Range
include Inject
end
# ===== code end =======
I saved that code as "test.rb"
then opened irb and typed include "test.rb".
Next I typed each of the following lines,
I get immediate results, fine:
[ 1, 2, 3, 4, 5 ].sum
[ 1, 2, 3, 4, 5 ].product
(1..5).sum
(1..5).product
('a'..'m').sum("Letters: ")
I typed these into irb, and they work:
p [ 1, 2, 3, 4, 5 ].sum
p [ 1, 2, 3, 4, 5 ].product
I type these into irb, they generate errors:
p (1..5).sum
p (1..5).product
p ('a'..'m').sum("Letters: ")
I added those lines to the test.rb file
to see what happens using the ruby interpreter:
%> ruby test.rb
These work, but produce no output:
[ 1, 2, 3, 4, 5 ].sum
[ 1, 2, 3, 4, 5 ].product
(1..5).sum
(1..5).product
('a'..'m').sum("Letters: ")
These also work (array):
p [ 1, 2, 3, 4, 5 ].sum
p [ 1, 2, 3, 4, 5 ].product
but these don't (similar to irb):
p (1..5).sum #generates an error
p (1..5).product #generates an error
p ('a'..'m').sum("Letters: ") #generates an error
However, this 2 step process works for the range:
aa = (1..5).sum
bb = (1..5).product
cc = ('a'..'m').sum("Letters: ")
p aa
p bb
p cc
What is different about how ranges and arrays process
this code, that p /array/ works but p /range/ doesn't?
#thanks
-- doug edmunds
19 March 2001