Ruby:使用new作为工厂

时间:2013-03-24 04:47:53

标签: ruby design-patterns

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

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。这有什么问题?

1 个答案:

答案 0 :(得分:2)

您不需要第二个*

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"