0

我正在开发一个小二十一点模拟器。我希望我的卡片类根据传递给 Card.new 的参数自动制作 Ace 而不是卡片。这是我所拥有的:

class Card

    include Comparable

    attr_reader :value, :name, :suit

    def self.new(*args, &block)
        *args[0] == "A" ? Ace.new(*args[1]) : super(*args, &block)
    end

    def initialize(name, suit)
        return Ace.new(suit) if name == "A"
        @name, @suit = name, suit
        @value = ["J", "Q", "K"].include?(name) ? 10 : name.to_i
    end

    def <=>(card)
        @value <=> card.value
    end

    def hash
        @value.hash
    end

    def to_s
        return "#{@name}#{@suit}"
    end

    alias eql? ==

end

class Ace < Card

    def initialize(suit)
        @name, @suit, @value = "A", suit, 11
    end

    def toggle
        @value = 1 if @value == 11
        @value = 11 if @value == 1
    end

end

当我运行所有这些时,不幸的是我得到了错误:

Blackjack Simulator/cards.rb:22: syntax error, unexpected tEQ, expecting '='if *args[0] == "A"

如果我没记错的话,我应该能够像普通数组一样读取 *args 。这里有什么问题?

4

1 回答 1

2

You don't need the second *.

def asdf_method(*args)
  args.join(' ') # At this point `args` already is an array
end

> asdf_method 1, 2, 3, 4
=> "1 2 3 4"
于 2013-03-24T04:51:13.560 回答