Suppose I have this : `my_array.sum(0) {|n| n ** 2 }
I can do yield if block_given?
But thent the block is not executed.
If I have this class :
class MyArray
attr_reader :array
def initialize(array)
@array = array
end
def sum(initial_value = 0)
return yield if block_given?
array.inject(:+) + initial_value
end
end
Where does the block get saved.
I can make a block with contains the block but I think there is a
I think you don't want to yield. You can capture the block like this:
def sum(initial_value = 0, &blk)
end
and then blk.call to execute the block, or use &blk to pass it to
another method. If I understood correctly, you want to map all
elements of the array to the result of passing each of them to the
block, then sum the result. If so, try something like this:
def sum(initial_value=0, &blk)
array.map(&blk).inject(initial_value, :+)
end
Untested, but could give you some ideas.
Jesus.
···
On Tue, Jun 24, 2014 at 9:58 PM, Roelof Wobben <r.wobben@home.nl> wrote:
Hello,
Suppose I have this : my_array.sum(0) {|n| n ** 2 }
I can do yield if block_given?
But thent the block is not executed.
If I have this class :
class MyArray
attr_reader :array
def initialize(array) @array = array
end
def sum(initial_value = 0)
return yield if block_given?
array.inject(:+) + initial_value
end
end
Where does the block get saved.
I can make a block with contains the block but I think there is a better way
?