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: | 112 |
Nodes: | 8 (1 / 7) |
Uptime: | 248:58:38 |
Calls: | 2,467 |
Calls today: | 1 |
Files: | 8,616 |
Messages: | 1,886,360 |