Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I pass an argument to array.map short cut? [duplicate]

Tags:

ruby

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?

like image 672
not_nil Avatar asked Mar 29 '12 20:03

not_nil


People also ask

How do you pass a parameter on a map in Python?

Passing Multiple Arguments to map() function Suppose we pass n iterable to map(), then the given function should have n number of arguments. These iterable arguments must be applied on given function in parallel. In multiple iterable arguments, when shortest iterable is drained, the map iterator will stop.

Can map take multiple arguments?

Using the Python map() function with multiple arguments functions. Besides using the Python map() function to apply single argument functions to an iterable, we can use it to apply functions with multiple arguments.

What are necessary arguments to write a map?

The map function has two arguments (1) a function, and (2) an iterable. Applies the function to each element of the iterable and returns a map object. The function can be (1) a normal function, (2) an anonymous function, or (3) a built-in function.


1 Answers

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.

like image 183
Andrew Grimm Avatar answered Sep 22 '22 01:09

Andrew Grimm