How to make calculations with elements of a Ruby array?

Asked

Viewed 270 times

0

    numeros = [1, 2]

class C
    def calcule_array(*numeros)
      puts a + b
    end

  end

  numeros = C.new

  puts numeros

I would like to know how to make calculations with whole elements that are inside an array in Ruby, I tried the above code but without success.

1 answer

1


Important points:

  • Remove the operator splat before the parameter name *numeros
  • You’re redeclareting the variable numeros when instances the class C

then you can use the method inject or reduce

numeros = [1, 2, 3, 4]

class C
  def calcule_array(numeros)
    puts numeros.reduce(:+)
  end
end

calcular = C.new
calcular.calcule_array(numeros)

Exit:

> 10

You can see it working in repl it.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.