CALCULATION METHOD IN RUBY TWO-DIMENSIONAL ARRA

Asked 2 years ago, Updated 2 years ago, 121 views

arrays=[7,5],[8,9,9,8],[13,13],[3,4,2,15,18],[3,2],[0,3,6,10,14,7],[7,10,9,11,14],
[4,8,5,8,1,10],[5,11,21,2],[11,18,19,17]]
=>
[12, 34, 26, 42, 5, 40, 51, 36, 39, 65]

I would like to have the result like this, but I would like you to tell me the procedure.

ruby

2022-09-30 21:40

1 Answers

You can use the Array#map method to execute the Array#sum method for each array

arrays=[
  [7, 5],
  [8, 9, 9, 8],
  [13, 13],
  [3, 4, 2, 15, 18],
  [3, 2],
  [0, 3, 6, 10, 14, 7],
  [7, 10, 9, 11, 14],
  [4, 8, 5, 8, 1, 10],
  [5, 11, 21, 2],
  [11, 18, 19, 17]
]

arrays.map(&:sum)#=>[12, 34, 26, 42, 5, 40, 51, 36, 39, 65]

If you are using a version earlier than Ruby 2.4, you can use the Enumerable #inject method.

arrays=[
  [7, 5],
  [8, 9, 9, 8],
  [13, 13],
  [3, 4, 2, 15, 18],
  [3, 2],
  [0, 3, 6, 10, 14, 7],
  [7, 10, 9, 11, 14],
  [4, 8, 5, 8, 1, 10],
  [5, 11, 21, 2],
  [11, 18, 19, 17]
]

arrays.map {|e|e.inject(:+)}#=>[12, 34, 26, 42, 5, 40, 51, 36, 39, 65]


2022-09-30 21:40

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.