Tyler Curtis Jowers Tyler Curtis Jowers - 3 years ago 62
Ruby Question

A function that makes an array of length b with all values equal to a, then takes the product (Ruby 2.3.3)

I need to define a function power(a,b) that takes the value a and repeats it b times and stores it in an array. Then takes the product of that array.

The idea is to be able to take any number a and raise it to the power of b using arrays.

Answer Source

Anything like this?

def power(a, b)
  Array.new(b, a).inject(1, :*)

power(2, 3)
=> 8
power(2, 4)
=> 16
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download