Quest of Virtue
Quest of Virtue

Reputation: 29

Wrong number of arguments (Ruby)

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

I have spent the last hour trying to fix this error. The error I get is:

wrong number of arugments (Argument Error)

Upvotes: 0

Views: 6034

Answers (3)

house9
house9

Reputation: 20624

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

Upvotes: 0

nicosantangelo
nicosantangelo

Reputation: 13736

You're missing the parens in the product method call; try this:

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

The problem is that you're actually accessing the [] method on product which will result on calling product without arguments and then slicing the result.

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

Since you can't pass 13 arguments to [] (which is the size of your second array), that's why you got wrong number of arguments (13 for 1..2).

Adding the parens will make your second array the argument of product and then will call each on the result, so:

['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

As you can see, you can drop the () and use a space, but in your case, you can't chain the each later on, that's why you'll have to add them.

Upvotes: 7

Arup Rakshit
Arup Rakshit

Reputation: 118299

You can also write as below :

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

Upvotes: 1

Related Questions