Instructions
Create a function product that takes an array of numbers and returns their product (multiplication).
Use the reduce method (also known as inject).
product([1, 2, 3, 4]) # => 24 (1 * 2 * 3 * 4)
product([5, 2]) # => 10
reduce takes an initial value and a block that combines elements:
ruby
[1, 2, 3].reduce(0) { |acc, n| acc + n } # => 6
Hints:
- Use .reduce(1) { |acc, n| acc * n }
- Start with 1 (identity for multiplication)
- Or use shorthand: .reduce(1, :*)
Your Code
def product(numbers)
numbers.reduce(1) { |acc, n| acc * n }
end
RSpec.describe "product" do
it "multiplies all numbers" do
expect(product([1, 2, 3, 4])).to eq(24)
end
it "returns 1 for empty array" do
expect(product([])).to eq(1)
end
it "handles single element" do
expect(product([5])).to eq(5)
end
it "handles zeros" do
expect(product([1, 2, 0, 4])).to eq(0)
end
it "handles negative numbers" do
expect(product([-2, 3])).to eq(-6)
end
end
Results
Click "Run Tests" to see results