Ruby: How to multiply several numbers?
Solution 1
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.
Solution 2
What you want is the #inject method
def multiple(*nums)
nums.inject(:*)
end
Inject will combine all of the elements in nums, using the operation specified ( * in this case ).
user2103064
Updated on June 14, 2022Comments
-
user2103064 almost 2 years
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.
-
Andrew Marshall about 11 years
numbers.reduce(1, :*)
may be preferred as it will return1
instead ofnil
if numbers is an empty array (no arguments passed). -
Theo about 11 yearsI would actually prefer to return
nil
when there are no numbers, there is no product if there are no numbers (but I realize my proposed solution returns 1 without input -- but I was trying not to complicate things too much). -
Andrew Marshall about 11 yearsI don't have a strong preference, depends on the intended use case; mostly just putting the option out there for the OP
:)
.