Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: How to multiply several numbers?

Tags:

math

ruby

I am trying to multiply any number of unknown arguments together to make a total.

 def multiply(*num)
  num.each { |i| puts num * num}
  end

multiply(2,3,4)
multiply(2,3,4,5,6,7)

Another attempt:

def multiply(num)
  num.to_i
   i = 0
   while i < num.length
   total = num * num

    return total
   end
end

multiply(2,3,4)
multiply(2,3,4,5,6,7)

I keep running into errors: (eval):73: undefined local variable or method `num_' for main:Object (NameError) from (eval):81

Some saying that Array needs to be Integer.

I've tried doing something I thought was suppose to be very simple program to write.

like image 708
user2103064 Avatar asked Dec 04 '25 05:12

user2103064


1 Answers

def multiply(*num) captures all arguments given to the method in an array. If you run multiply(1, 2, 3, 4) then num will equal [1, 2, 3, 4]. So in both your attempts you're trying to multiply a whole array with itself (num * num), which is not going to work.

Others have suggested solutions to how to write the multiply method correctly, but let me give you a correct version of your first attempt and explain it properly:

def multiply(*numbers)
  result = 1
  numbers.each { |n| result = result * n }
  result
end

As in your attempt I capture all arguments in an array, I call mine numbers. Then I declare a variable that will hold the result of all the multiplications. Giving it the value of 1 is convenient because it will not affect the multiplications, but I could also have shifted off the first value off of the numbers array, and there are other solutions.

Then I iterate over all the numbers with each, and for each number I multiply it with the current result and store this as the new result (I could have written this shorter with result *= n).

Finally I return the result (the last value of a method is what will be returned by the method).

There are shorter ways of doing the same thing, others have suggested using numbers.reduce { |n, result| n * result }, or even numbers.reduce(:*), but even though they are shorter, they are pretty cryptic and I assume they don't really help you get things working.

like image 68
Theo Avatar answered Dec 06 '25 20:12

Theo