Ruby:方法体中的类定义

时间:2014-11-17 16:56:18

标签: ruby

当我运行我的代码时,我收到以下错误:

Card.rb:51: class definition in method body
Card.rb:74: syntax error, unexpected end-of-input, expecting keyword_end

我检查了第51和74行以及所有相关的块,但我找不到任何错误。似乎所有end语句都是对齐的。当我取出Card类中的私有方法时,错误会停止,但我无法准确指出错误。我有正确数量的结束语句,为什么我收到class definition in method body错误

class Card

  attr_reader :suit, :rank

  def initialize(suit, rank)
    @suit = suit
    @rank = rank
  end

  def face_card?
    @rank > 10
  end

  def to_s
    suitName = suitString()
    rankName = rankString()
    rankName " of " + suitName
  end

  private 

  def rankString
    if @rank <= 10
      @rank
    else if @rank == 11
      "Jack"
    else if @rank == 12
      "Queen"
    else if @rank == 13
      "King"
    else
      "Unknown rank"
    end
  end

  def suitString
    if @suit == :spades
      "Spades"
    else if @suit == :clubs
      "Clubs"
    else if @suit == :hearts
      "Hearts"
    else if @suit == :diamonds
      "Diamonds"
    else
      "Unknown Suit"
    end
  end
end

class Deck
  def initialize
    @cards = []
    suits = [:hearts, :diamonds, :spades, :clubs]
    suits.each do |suit|
      12.times do |rank|
        @cards << Card.new(suit, (rank + 1))
      end
    end
  end

  def shuffle
    @cards.shuffle!
  end

  def draw(n = 1)
    @cards.pop(n)
  end

  def count
    @cards.count
  end
end

2 个答案:

答案 0 :(得分:3)

您的代码应包含elsif而不是else if,但您也可以轻松使用case

示例:正确使用elsif的方法:

def suitString
  if @suit == :spades
    "Spades"
  elsif @suit == :clubs
    "Clubs"
  elsif @suit == :hearts
    "Hearts"
  elsif @suit == :diamonds
    "Diamonds"
  else
    "Unknown Suit"
  end
end

使用case

def suitString
  result = case @suit
           when :spades then #then is optional
               "Spades"
             when :clubs
               "Clubs"
             when :hearts
               "Hearts"
             when :diamonds
               "Diamonds"
             else
               "Unknown Suit"
           end
  return result #return is optional
end

答案 1 :(得分:0)

else if语句更改为elsif。使用正确的Ruby语法