查看rspec测试我再次需要使用define创建一个方法,并让它能够使用多个参数。我想我需要将这些参数放入数组中。我不确定如何设置我的参数,所以他们进入一个数组,使参数无限,所以有人可以做 def sum(1,3,4,12,32,18,17,22)或添加或多或少。
这是我的rspec测试,以确保它的工作
describe "sum" do
it "computes the sum of an empty array" do
sum([]).should == 0
end
it "computes the sum of an array of one number" do
sum([7]).should == 7
end
it "computes the sum of an array of two numbers" do
sum([7,11]).should == 18
end
it "computes the sum of an array of many numbers" do
sum([1,3,5,7,9]).should == 25
end
end
所以我的问题是如何让define方法将参数输入到数组中?
答案 0 :(得分:0)
def sum(*parameters)
# ...
end
当您调用parameters=[1, 3, 5, 7, 9]
时,会生成sum(1, 3, 5, 7, 9)
。请注意星号*
(此处称为“splat operator”)。
然而,在你的RSpec中,你正在调用sum([1, 3, 5, 7, 9])
,所以如果你继续使用那个测试它只是一个正常的数组参数。
答案 1 :(得分:0)
def sum(*params)
params.length == 0 ? 0 : params.inject(:+)
end
sum(1, 2, 3) => 6
sum(5, 8) => 13
sum(1) => 1
sum() => 0