I discovered tonight that Ruby’s Symbol#to_proc handles additional yielded values beyond the first as arguments to the method invocation. In other words, these two method calls are equivalent:
yields_three{ |a,b,c| a.foo(b,c) }
yields_three( &:foo )
I thought this could be a powerful (or at least amusing) idiom to explore, and so I tried the following:
class Player
def add_score( points )
@score += points
end
end
my_array_of_players.zip( my_array_of_turn_scores ).each(&:add_score)
Unfortunately, this doesn’t work:
NoMethodError: undefined method `add_score' for [<#Player 'Phrogz'>, 42]:Array
So, the question: can you write an Enumerator#explicitly method that instead of yielding a single array of values yields all of them explicitly?
If you are successful, these should work:
pairs = [[1,2],[3,4],[5,6]]
pairs.map.explicitly(&:+) #=> [3,7,11]
pairs.map.explicitly(&:*) #=> [2,12,30]
class String
def say_hey(b)
puts "#{self} says 'hey' to #{b}"
end
end
('a'..'d').each_cons(2).explicitly(&:say_hey)
#=> "a says 'hey' to b"
#=> "b says 'hey' to c"
#=> "c says 'hey' to d"
Here’s how you can do it:
I executed your tests against this and the proper results are returned.
UPDATE: Changed to not capture the block explicitly.