Ruby on Rails Switch

This question already has an answer here:

  • How to write a switch statement in Ruby? 21 answers

  • I assume you refer to case/when.

    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
    

    or

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

    EDIT

    Something that maybe not everyone knows about but what can be very useful is that you can use regexps in a case statement.

    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}"
    
    链接地址: http://www.djcxy.com/p/25636.html

    上一篇: 为什么在Ruby中`返回a或b`是一个void值表达式错误?

    下一篇: Ruby on Rails开关