2013-07-13 117 views
0
class Testdeck 
    attr_accessor :cards 

    def initialize 
     @cards = [] 
     counter = 0 
     ['H','C', 'S', 'D'].product['2','3','4','5','6','7','8','9','10','J','K','Q','A'].each do |arr| 
      @cards << Card.new(arr[0], arr[1]) 
     end 
    end 
end 

zen = Testdeck.new 
puts zen.cards.pop 

我花了最后一小时试图解决这个错误。我得到的错误是:错误的参数数量(红宝石)

wrong number of arugments (Argument Error) 
+4

你能如此种类并附上带有回溯的FULL错误消息? –

回答

7

你错过了在product方法调用的括号;试试这个:

def initialize 
    @cards = [] 
    counter = 0 
    ['H','C', 'S', 'D'].product(['2','3','4','5','6','7','8','9','10','J','K','Q','A']).each do |arr| 
     @cards << Card.new(arr[0], arr[1]) 
    end 
end 

的问题是,你实际上访问的product[]方法,这将导致在调用product没有参数,然后切片的结果。

['H','C', 'S', 'D'].product # == [["H"], ["C"], ["S"], ["D"]] 

既然你不能传递13个参数[](这是你的第二个数组的大小),这就是为什么你有wrong number of arguments (13 for 1..2)

添加括号将使你的第二个阵列的product的说法则将调用each的结果,所以:

['H','C', 'S', 'D'].product[1, 2] # == [["C"], ["S"]] 

['H','C', 'S', 'D'].product [1, 2] == ['H','C', 'S', 'D'].product([1, 2]) # == [["H", 1], ["H", 2], ["C", 1], ["C", 2], ["S", 1], ["S", 2], ["D", 1], ["D", 2]] 
         ^important separation here 

正如你所看到的,你可以删除()和使用空间,但在你的情况下,你以后不能链接each,这就是为什么你必须添加它们。

+0

它的工作,非常赞赏 –

+1

不客气:)。请接受一个答案,以便问题不会公开。 – NicoSantangelo

1

你也可以写如下:

(['H','C', 'S', 'D'].product ['2','3','4','5','6','7','8','9','10','J','K','Q','A']).each do |arr| 
0

见@NicoSantangelo回答是正确的,这里是用map初始化@cards实例变量的一个版本

suites = ['H', 'C', 'S', 'D'] 
values = ('2'..'10').to_a + ['J', 'K', 'Q', 'A'] 

@cards = suites.product(values).map do |parts| 
    Card.new(parts[0], parts[1]) 
end