How to make calculations with elements of an array in Ruby? [closed]

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 I can do calculations with integers that are inside an array in Ruby, I tried the above code but without success.

    
asked by anonymous 04.11.2018 / 21:31

1 answer

1

Important points:

  • Remove the splat operator that is before the parameter name *numeros
  • You are redeclaring the variable numeros when you instantiate the class C

Then you can use the inject or < a href="http://ruby-doc.org/core-2.5.3/Enumerable.html#method-i-reduce"> reduce

numeros = [1, 2, 3, 4]

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

calcular = C.new
calcular.calcule_array(numeros)

Output:

> 10

You can see it working at repl.it

    
04.11.2018 / 21:58