简体   繁体   中英

Is there a way to apply multiple method by one liner in ruby?

There is an array like this:

a = [1,2,3,4]

I want to get the return values of size and sum like this.

size = a.size
sum = a.sum

Is there a way to get both values by a one-liner like this?

size, sum = a.some_method(&:size, &:sum)

In Ruby, you can do multiple assignments in one line:

size, sum = a.size, a.sum

It doesn't make it more readable, though.

You could do this:

a = [1,2,3,4]
methods = [:size, :max, :min, :first, :last]

methods.map { |m| a.send m }
  #=> [4, 4, 1, 1, 4]

另一个可能的解决方案:

size, sum = a.size, a.reduce { |a,b| a = a + b }

Previous answers are correct, but if OP was actually concerned about walking the array multiple times, then array.size does not walk the array, it merely returns the length, thus there is no saving from a oneliner in that regard.

On the other hand, if size was just an example and the question is more about making multiple operations on an array in one go, then try something like this:

arr = [1,2,3,4,5,6]

product,sum = arr.inject([1,0]){|sums,el| [sums[0]*el, sums[1]+el]}
# => [720, 21]

That is, inject the array with multiple initial values for the results and then calculate new value for every element.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM