Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shorter way to pass every element of an array to a function

Tags:

ruby

In Ruby, you can apply a map function to every element of an array:

@files.map { |f| f.read) }

For which there is the syntactic sugar:

@files.map(&:read)

Is there any equivalent for

@files.map { |f| read(f) } 

That is terser, similar to the above?

like image 344
user2398029 Avatar asked Dec 12 '12 07:12

user2398029


People also ask

How do you pass an entire array to a function?

To pass an entire array to a function, only the name of the array is passed as an argument. result = calculateSum(num); However, notice the use of [] in the function definition. This informs the compiler that you are passing a one-dimensional array to the function.

How do you pass an entire array to a function in Java?

To pass an array to a function, just pass the array as function's parameter (as normal variables), and when we pass an array to a function as an argument, in actual the address of the array in the memory is passed, which is the reference.

What is reduce () in Javascript?

The reduce() method executes a user-supplied "reducer" callback function on each element of the array, in order, passing in the return value from the calculation on the preceding element. The final result of running the reducer across all elements of the array is a single value.


1 Answers

You can do this

@files.map(&method(:read))

But be aware though about performance.

like image 88
oldergod Avatar answered Oct 21 '22 17:10

oldergod