Hello Ruby list!
I have recently started playing with Ruby, and I’m currently being
puzzled by something that doesn’t work the way I expect it to. Here’s an
example script:
A function that yields the double of each member of a list
def doubleMe(list)
list.each do |value|
yield value * 2
end
end
A function that yields values 1-5
def yieldValues
yield 1
yield 2
yield 3
yield 4
yield 5
end
A list
myList = [1, 2, 3, 4, 5]
Yield double the value of each item in my list to a block which says
something nice about Ruby - works.
doubleMe(myList) { |value| puts “#{value} reasons to love Ruby” }
Define a Proc object which does the same as the block above
outPutter = proc do |value|
puts "#{value} reasons to love Ruby"
end
Use the Proc object as the block for function yieldValues - works.
yieldValues &outPutter
Modify the Array class to include an “eachDouble” method
module Doubler
def eachDouble
each do |value|
yield value * 2
end
end
end
class Array
include Doubler
end
Use the Proc object as a block for this new method - works.
myList.eachDouble &outPutter
Doesn’t work. Why?
doubleMe(myList) &outPutter
···
Can anyone shed any light on why the final line in this script produces
an error?
thanks,
Dominic