【问题标题】:Does ruby's case statement fall through?ruby 的案例陈述是否失败?
【发布时间】:2015-07-16 01:25:01
【问题描述】:

我正在用 ruby​​ 编写一个刽子手游戏,我想使用一个案例语句来确定对应于一些错误猜测的身体部位。我使用用于国际象棋和connect-4等其他游戏的棋盘类制作了这个游戏,因为我有一个序列化棋盘类的方法,允许我保存和加载游戏而无需任何额外代码。为了保存游戏,我需要一些方法来确定刽子手猜错的次数,而无需向棋盘类添加额外的变量。为了解决这个问题,我在棋盘类上使用了一个名为 history 的实例变量,它可用于将游戏中的移动推送到棋盘历史。当棋盘被序列化时,历史记录也会被保存,游戏可以读取并用于确定错误的猜测。

在刽子手游戏中,我有一个称为读取历史记录的方法(我将其用于所有游戏,因为它解决了上述序列化问题)。 read_history 方法负责读取过去的猜测,显示它们,并确定错误猜测的数量。然后将此数字传递给 hang 方法,该方法确定要添加刽子手的哪些身体部位。

def hang(incorrect)
    case incorrect
    when 0 
        @hangman = ["   ", "   ", "   "]
        break
    when 7 
        @hangman[2][2] = '\\'
    when 6
        @hangman[2][0] = '/'
    when 5
        @hangman[2][1] = '*'
    when 4
        @hangman[1][2] = '\\'
    when 3
        @hangman[1][0] = '/'
    when 2 
        @hangman[1][1] = '|'
    when 1
        @hangman[0][1] = 'o'
    end
end

如果我在 java 中编写此代码,并将值 5 传递给上述方法,它将读取该语句,直到它命中“when 5”或 java 术语中的“case 5:”。它会注意到语句中没有中断,并将在列表中向下移动执行“案例 4:”中的代码并重复直到找到中断。但是如果传递了 0,它将执行代码,查看中断,并且不会执行其他语句。

我想知道 Ruby 是否能够像 java 那样使用 case 语句,就像它们落入下一条语句一样。对于我的特定问题,我知道我可以使用 0.upto(incorrect) 循环并以这种方式运行案例,但我想知道 ruby​​ 中使用的 case 语句与 switch-case 的异同在java中使用

【问题讨论】:

  • 您要查找的术语是“fall through”,如“this case fall through to next case”。

标签: ruby


【解决方案1】:

不,Ruby 的 case 语句不会像 Java 那样失败。实际上只运行了一个部分(或其他部分)。但是,您可以在单个匹配项中列出多个值,例如喜欢this site shows。

print "Enter your grade: "
grade = gets.chomp
case grade
when "A", "B"
  puts 'You pretty smart!'
when "C", "D"
  puts 'You pretty dumb!!'
else
  puts "You can't even use a computer!"
end

它在功能上相当于一个巨大的 if-else。 Code Academy 的page on it 建议使用逗号来提供多个选项。但是你仍然不能执行多个逻辑分支。

【讨论】:

  • 这不是公认的答案,因为它不适用于 OP 用例。这仍然是很好的信息
【解决方案2】:

它不会失败。

Ruby just doesn't have the same behavior as Java for this type of statement.

如果你想模拟跌倒行为,你可以这样做:

def hang(incorrect)
    @hangman = ["   ", "   ", "   "]
    @hangman[2][2] = '\\' if incorrect > 6
    @hangman[2][0] = '/' if incorrect > 5
    @hangman[2][1] = '*' if incorrect > 4
    @hangman[1][2] = '\\' if incorrect > 3
    @hangman[1][0] = '/' if incorrect > 2
    @hangman[1][1] = '|' if incorrect > 1
    @hangman[0][1] = 'o' if incorrect > 0

    @hangman
  end

【讨论】:

  • 谢谢你,这正是我想要的
  • 您链接到的 ruby​​ 文档信息不会直接确认/否认 ruby​​ 的案例陈述是否通过。
猜你喜欢
  • 2012-08-14
  • 1970-01-01
  • 2012-08-11
  • 1970-01-01
  • 2012-03-08
  • 2012-06-13
  • 2023-04-10
  • 2010-10-30
  • 2016-05-13
相关资源
最近更新 更多