Ruby:方法体中的类定义

标签 ruby

<分区>

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

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

我检查了第 51 行和第 74 行以及所有相关的 block ,但我找不到任何错误。似乎所有 end 语句都对齐了。当我取出 Card 类中的私有(private)方法时,错误停止,但我无法准确指出错误所在。我有正确数量的结束语句,为什么我收到 方法主体中的类定义 错误

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

最佳答案

您的代码应该包含 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

关于Ruby:方法体中的类定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26977780/

相关文章:

ruby - 收到错误 "nil:NilClass (No MethodError)"

ruby - Sinatra session 自动销毁

ruby-on-rails - 如何在事件管理仪表板 - Rails 中呈现自定义表单?

ruby - 是否可以在这里使用标准断言而不是模拟期望?

ruby-on-rails - Rspec 跳过 Controller 中的设计操作 - sign_in_and_redirect

ruby-on-rails - 任何示例如何通过 Rails 中的延迟作业进行批量更新

ruby-on-rails - 将 3 个结果包装在一个 div 中

ruby - 在两个单独的页面上抓取需要登录用户名和密码的站点

css - 日历:date_started 到 Date.current?

mysql - 在 Windows 上为 ruby​​ 2.0.0 安装 mysql2 gem 时出错