鲁比“当”关键字在 case 语句中不使用 ==。它有什么用?
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?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
大小写比较使用
===
而不是==
。对于许多对象,===
和==
的行为是相同的,请参阅Numeric
和String
:但是对于其他类型的对象
===
可能意味着很多东西,完全取决于接收者。对于类的情况,
===
测试对象是否是该类的实例:对于 Range,它检查对象是否属于该范围:
对于 Procs,
=== 实际上调用了
Proc
:对于其他对象,检查它们的
===
定义以揭示它们的行为。这并不总是显而易见的,但它们通常有某种意义。以下是一个将所有内容放在一起的示例:
请参阅此链接以获取更多信息:http://www.aimred.com/news/developers/2008/08/14/unlocking_the_power_of_case_equality_proc/
Case comparisons use
===
rather than==
. For many objects the behaviour of===
and==
is the same, seeNumeric
andString
: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:For Range it checks whether an object falls in that range:
For Procs,
===
actually invokes thatProc
: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:
See this link for more info: http://www.aimred.com/news/developers/2008/08/14/unlocking_the_power_of_case_equality_proc/
在 case 语句中,比较是使用
===
运算符完成的。因此,您的代码将转换为以下内容:
不同的类以不同的方式定义
===
:Class
类定义===
以便进行测试右侧操作数 (x
) 是否是左侧操作数 (User
) 命名的类的实例。因此,User === x
被评估为false
也就不足为奇了。相反,User === u
(u = User.new) 为true
。In case statement , the comparison is done using
===
operator.So your code is translated to following:
Different class define
===
in different way:The
Class
class define===
so that it tests whether the righthand operand (x
)is an instance of the class named by the lefthand operand (User
). So , It is not surprise thatUser === x
will be evaluated asfalse
. Instead,User === u
(u = User.new) istrue
.