【问题标题】:Ruby on Rails Switch [duplicate]Ruby on Rails Switch [重复]
【发布时间】:2011-09-30 00:12:34
【问题描述】:

谁能提供一个例子来说明如何在 Ruby 中使用 switch case 来处理变量?

【问题讨论】:

    标签: ruby switch-statement


    【解决方案1】:

    我假设您指的是案例/何时。

    case a_variable # a_variable is the variable we want to compare
    when 1    #compare to 1
      puts "it was 1" 
    when 2    #compare to 2
      puts "it was 2"
    else
      puts "it was something else"
    end
    

    puts case a_variable
    when 1
      "it was 1"
    when 2
      "it was 2"
    else
      "it was something else"
    end
    

    编辑

    也许不是每个人都知道,但非常有用的是您可以在 case 语句中使用正则表达式。

    foo = "1Aheppsdf"
    
    what = case foo
    when /^[0-9]/
      "Begins with a number"
    when /^[a-zA-Z]/
      "Begins with a letter"
    else
      "Begins with something else"
    end
    puts "String: #{what}"
    

    【讨论】:

    • 非常感谢。我可以用 params[:id] 替换 a_variable 吗?
    • 当然,只要确保您在比较相同类型的变量,例如“1”不等于 1。但是“1”.to_i 等于 1(to_i 将字符串转换为整数)。如果要将 params[:id] 与整数进行比较,则需要执行“case params[:id].to_i”。用“case”测试 params[:id] 对我来说有点奇怪,你确定你在做什么吗?
    • 谢谢伙计。那真的很有帮助。我认为这是问题所在!
    • 与传统的 switch..case 有一些不同。最值得注意的是没有级联到下一个项目。另一个是您可以在每个when 中列出多个(逗号分隔)项目。最后,它们不仅匹配相等,还匹配 === 运算符,因此:String === "thing" 为真,因此 when String then whatever 将匹配。
    • 重要提示: 与许多其他语言中的switch 语句不同,Ruby 的case 没有fall-through,因此无需以when 结尾break.
    猜你喜欢
    • 2012-11-23
    • 2012-04-04
    • 2012-07-05
    • 2014-11-04
    • 2014-01-08
    • 2013-02-18
    • 2019-01-27
    • 2014-12-20
    • 2016-04-24
    相关资源
    最近更新 更多