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

3 回答 3

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

问题是您实际上正在访问将导致不带参数调用然后切片结果的[]方法。productproduct

['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后面链接,这就是您必须添加它们的原因。

于 2013-07-13T14:35:15.947 回答
1

你也可以这样写:

(['H','C', 'S', 'D'].product ['2','3','4','5','6','7','8','9','10','J','K','Q','A']).each do |arr|
于 2013-07-13T14:39:37.163 回答
0

See @NicoSantangelo answer it is the correct one, here is a version using map to initialize the @cards instance variable

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
于 2013-07-13T14:55:10.930 回答