代码之家  ›  专栏  ›  技术社区  ›  maček

Ruby'when'关键字在case语句中不使用==。它用什么?

  •  8
  • maček  · 技术社区  · 14 年前

    x == User 退货 true case x 语句不运行与 User

    u = User.new
    # => #<User:0x00000100a1e948>
    
    x = u.class
    # => User
    
    x == User
    # => true
    
    case x
    when User
      puts "constant"
    when "User"
      puts "string"
    else
      puts "nothing?"
    end
    # => nothing?
    
    2 回复  |  直到 14 年前
        1
  •  21
  •   horseyguy    14 年前

    案例比较使用 === == . 对许多物体来说 === == Numeric String

    5 == 5 #=> true
    5 === 5 #=> true
    
    "hello" == "hello" #=> true
    "hello" === "hello" #=> true
    

    但对于其他类型的物体 === 可能意味着很多事情,完全取决于接收者。

    就班级而言, 测试对象是否是该类的实例:

    Class === Class.new #=> true. 
    

    对于范围,它检查对象是否在该范围内:

    (5..10) === 6 #=> true
    

    === Proc :

    multiple_of_10 = proc { |n| (n % 10) == 0 }
    multiple_of_10 === 20 #=> true (equivalent to multiple_of_10.call(20))
    

    对于其他对象,请检查其定义 === 揭露他们的行为。这并不总是显而易见的,但它们通常是有意义的。。

    case number
    when 1
        puts "One"
    when 2..9
        puts "Between two and nine"
    when multiple_of_10
        puts "A multiple of ten"
    when String
        puts "Not a number"
    end  
    

    有关详细信息,请参见此链接: http://www.aimred.com/news/developers/2008/08/14/unlocking_the_power_of_case_equality_proc/

        2
  •  2
  •   pierrotlefou    14 年前

    在case语句中,比较是使用 ===

    因此,您的代码被转换为:

    case x
    when User === x 
        puts "Constant"
    when "User" === x
        puts "string"
    else 
        puts "nothing"
    end
    

    ===

    这个 Class 类定义 === x )是由左手操作数命名的类的实例( User ). 所以,这并不奇怪 User === x false . 相反, User === u (u=用户.新建)是 true

    irb(main):001:0> class User
    irb(main):002:1> end
    => nil
    irb(main):003:0> u = User.new
    => #<User:0xb7a90cd8>
    irb(main):004:0> User === u.class
    => false
    irb(main):005:0> User === u
    => true