ArgumentError: wrong number of arguments (given 1, expected 0)(1..5).reduce(:+)15
(1..5).reduce(&:+)15
['x', 'y', 'z'].map(:upcase)
['x', 'y', 'z'].map(&:upcase)["X", "Y", "Z"]
Why does `reduce' work passing both `&:+' _and_ `:+', but `map' seems to accept only `&:upcase' (but not `:upcase`)?
ArgumentError: wrong number of arguments (given 1, expected 0)(1..5).reduce(:+)15
(1..5).reduce(&:+)15
['x', 'y', 'z'].map(:upcase)
from (pry):3:in `map'
['x', 'y', 'z'].map(&:upcase)["X", "Y", "Z"]
Docs for `Enumerable#reduce' say:
""
Combines all elements of enum by applying a binary
operation, specified by a block or a symbol that names a
method or operator.
""
Docs `Enumerable#map' say:
""
Returns a new array with the results of running block once
for every element in enum.
""
So, is that `reduce' takes both a block and a symbol, while map takes
only a block?
And if so, is that some Ruby inconsistency?
On 28.06.2018 11:25, Fernando Basso wrote:
Why does `reduce' work passing both `&:+' _and_ `:+', but `map' seems to
accept only `&:upcase' (but not `:upcase`)?
ArgumentError: wrong number of arguments (given 1, expected 0)(1..5).reduce(:+)15
(1..5).reduce(&:+)15
['x', 'y', 'z'].map(:upcase)
from (pry):3:in `map'
['x', 'y', 'z'].map(&:upcase)["X", "Y", "Z"]
Docs for `Enumerable#reduce' say:
""
Combines all elements of enum by applying a binary
operation, specified by a block or a symbol that names a
method or operator.
""
Docs `Enumerable#map' say:
""
Returns a new array with the results of running block once
for every element in enum.
""
So, is that `reduce' takes both a block and a symbol, while map takes
only a block?
Yes.
And if so, is that some Ruby inconsistency?
Yes.
Actually I am surprised that #reduce / #inject accepts a single Symbol.
But these methods have some subtleties in argument handling anyway, so
maybe I should not be surprised.
Kind regards
robert
Sysop: | Keyop |
---|---|
Location: | Huddersfield, West Yorkshire, UK |
Users: | 286 |
Nodes: | 16 (3 / 13) |
Uptime: | 91:24:36 |
Calls: | 6,497 |
Calls today: | 8 |
Files: | 12,100 |
Messages: | 5,277,694 |