Ruby的when关键字在case语句中不使用==.它有什么用? [英] Ruby `when' keyword does not use == in case statement. What does it use?

查看:202
本文介绍了Ruby的when关键字在case语句中不使用==.它有什么用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

x == User返回true,但是case x语句不运行与User关联的块.这是怎么回事?

x == User returns true, but case x statement does not run the block associated with User. What's happening here?

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?

推荐答案

案例比较使用===而不是==.对于许多对象,=====的行为是相同的,请参见NumericString:

Case comparisons use === rather than ==. For many objects the behaviour of === and == is the same, see Numeric and String:

5 == 5 #=> true
5 === 5 #=> true

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

但是对于其他种类的对象,===可能意味着很多事情,完全取决于接收者.

But for other kinds of object === can mean many things, entirely depending on the receiver.

对于类,===测试对象是否是该类的实例:

For the case of classes, === tests whether an object is an instance of that class:

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

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

For Range it checks whether an object falls in that range:

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

对于Procs,===实际上会调用Proc:

For Procs, === actually invokes that Proc:

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

对于其他对象,请检查其对===的定义以发现其行为.这并不总是很明显,但是它们通常具有某种意义..

For other objects, check their definition of === to uncover their behaviour. It's not always obvious, but they usually make some kind of sense..

以下是将所有内容放在一起的示例:

Here is an example putting it all together:

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/

See this link for more info: http://www.aimred.com/news/developers/2008/08/14/unlocking_the_power_of_case_equality_proc/

这篇关于Ruby的when关键字在case语句中不使用==.它有什么用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆