Given the following array a
:
a = [1, 2, 3, 4, 5]
How do I do:
a.map { |num| num + 1 }
using the short notation:
a.map(&:+ 1)
or:
a.map(&:+ 2)
where 1 and 2 are the arguments?
Given the following array a
:
a = [1, 2, 3, 4, 5]
How do I do:
a.map { |num| num + 1 }
using the short notation:
a.map(&:+ 1)
or:
a.map(&:+ 2)
where 1 and 2 are the arguments?
You can't do it like this. The &
operator is for turning symbols into procs.
a = [1, 2, 3, 4, 5]
puts a.map(&:to_s) # prints array of strings
puts a.map(&:to_s2) # error, no such method `to_s2`.
&
is a shorthand for to_proc
:
def to_proc
proc { |obj, *args| obj.send(self, *args) }
end
It creates and returns new proc. As you see, you can't pass any parameters to this method. You can only call the generated proc.
Symbol#to_proc
, because it lacks function composition and currying. Are you coming from a functional background? –
Needlework to_proc
method. You can define to_proc
on Array
to do what you want. See Boris Stitnicky's answer here –
Decree &
does not turn a symbol or anything with to_proc
to a proc. It turns a proc to a block. Applying to_proc
is due to implicit class casting. –
Foreclosure In this case you can do
a.map(&1.method(:+))
But only because 1 + x is usually the same as x + 1.
Here is a discussion of this practice in a performance context.
You can't do it like this. The &
operator is for turning symbols into procs.
a = [1, 2, 3, 4, 5]
puts a.map(&:to_s) # prints array of strings
puts a.map(&:to_s2) # error, no such method `to_s2`.
&
is a shorthand for to_proc
:
def to_proc
proc { |obj, *args| obj.send(self, *args) }
end
It creates and returns new proc. As you see, you can't pass any parameters to this method. You can only call the generated proc.
Symbol#to_proc
, because it lacks function composition and currying. Are you coming from a functional background? –
Needlework to_proc
method. You can define to_proc
on Array
to do what you want. See Boris Stitnicky's answer here –
Decree &
does not turn a symbol or anything with to_proc
to a proc. It turns a proc to a block. Applying to_proc
is due to implicit class casting. –
Foreclosure You cannot do it with map
. But look at Facets' Enumerable#map_send:
require 'facets'
[1, 2, 3].map_send(:+, 1)
#=> [2, 3, 4]
Writing your own implementation is pretty straightforward:
module Enumerable
def map_send(*args)
map { |obj| obj.send(*args) }
end
end
If you really need that you can use Ampex library, but I don't know if it is still maintained.
© 2022 - 2024 — McMap. All rights reserved.
[1, 2, 3, 4, 5].map(&:next) # => [2, 3, 4, 5, 6]
– Chloro