Leonardo Marzochi
Leonardo Marzochi

Reputation: 83

Multiplying sub-arrays itens in Ruby

Ok, i want multiply the numbers inside a sub-array that i've created using: each_slice(2)

so far i got:

inputArray = [1, 2, 3, 4, 5, 6]
inputArray.each_slice(2).to_a  #[[1, 2], [3, 4], [5, 6]]

whats i've already tried:

if inputArray.length % 2 == 0
   newArr = inputArray.each_slice(2).to_a
   newArr = newArr.max #using .max works, but it doesn't always return the rigth value
   newArr.inject(:*)

i'm trying to achieve this result:

#[[2],[12],[30]]

As a novice to Ruby and programming in general i'm out of ideas

Upvotes: 0

Views: 74

Answers (2)

SRack
SRack

Reputation: 12203

You're along the right lines with each_slice. This should do it for you:

input_array.each_slice(2).map { |x, y| [x * y] }
=> [[2], [12], [30]]

You don't need the to_a in there, though it works with a nested array if need be.

This iterates through each sub-array (or slice) and return an array of whatever the block evaluates to for each pair. For example, here it multiplies the two elements together and wraps them in a one-item sub-array.

Hope that helps - let me know if you have any questions!

Upvotes: 3

tadman
tadman

Reputation: 211590

You've almost got it, but you need to combine things the right way:

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

list.each_slice(2).map { |l| [ l.inject(:*) ] }
# => [[2], [12], [30]]

The inject operation needs to be moved inside the map because you're not transforming just one of the items, but each of them in turn.

Upvotes: 2

Related Questions