2013-11-25 37 views
0

看看rspec測試我再一次需要使用define創建一個方法,並讓它能夠使用多個參數。我想我需要將這些參數放入數組中。我不確定如何設置我的參數,以便它們進入數組並使參數無限,因此有人可以執行def sum(1,3,4,12,32,18,17,22)或添加或多或少。Ruby:如何將def參數放入數組中?

這是我的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 

所以我的問題是如何獲取的定義方法輸入的參數爲數組?

回答

0
def sum(*parameters) 
    # ... 
end 

會讓parameters=[1, 3, 5, 7, 9]當你調用sum(1, 3, 5, 7, 9)。請注意星號*(這裏稱爲「splat運算符」)。

然而,在你的RSpec的,你打電話sum([1, 3, 5, 7, 9]),因此,如果您繼續使用該測試只是一個正常的數組參數。

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 
+0

不通過規範'[]' – Dty

+0

已更新爲不帶參數傳遞。 – Casey