Ruby 程序中的案例代码无法处理传递的值

Case code in Ruby program not working with a passed value

已经为程序编写了一些测试代码,试图传递 2 个值,一个文件和一个数字。以下根本不起作用,但如果我有类似 puts "test" 的东西(在案例之外),它就起作用了。

def read_album(music_file, number)
    puts number #(this does something)
    case number.to_i
    when(number > 1)
            puts "done"
    when(number < 2)
            puts "something"
    when(number == 3)
        puts "none of this inside case is working"
    end
end

def main()
    a_file = File.new("albums.txt", "r")
    print("Choose album id: ")
    choice_of_album = gets().to_i
    read_album(a_file, choice_of_album)
end

main()

您需要从 case 语句中删除 number.to_i

或者做类似的事情

case number.to_i
    when 1..2 
        puts "foo"
    when 3..100
        puts "bar"
    else 
        puts "foobar"
    end
end

来自 Ruby 文档

Case statements consist of an optional condition, which is in the position of an argument to case, and zero or more when clauses. The first when clause to match the condition (or to evaluate to Boolean truth, if the condition is null) “wins”, and its code stanza is executed. The value of the case statement is the value of the successful when clause, or nil if there is no such clause.

你的版本会像

if (number > 1) === number.to_i

并且由于您将数字与布尔表达式进行比较,因此计算结果不会为真。如果你在 case 语句中有一个 else,这将被调用。

您的 case 并没有按照您的想法行事。赋给 when 的表达式被求值,结果将使用大小写相等运算符 ===case 值进行比较。 number > 1 等表达式的计算结果为 truefalse。将此结果与 Ruby.

中的整数进行比较是没有意义的

您应该直接与常数进行比较。

case number
when 1
  # handle 1
when 2
  # handle 2
when 3
  # handle 3
else
  # handle unknown case; error?
end

请注意,其他 classes 可能会覆盖 === 以提供有用的行为。例如,RangeRegexp class 就是这样做的。

case number
when 1..3
  # handle 1, 2 and 3
end

case string
when /pattern/
  # handle pattern
end

值得注意的是,Proc class 也这样做!

def greater_than(n)
  proc { |x| x > n }
end

case number
when greater_than(2)
  # handle number > 2
end