gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 06:51:40 26 4
gpt4 key购买 nike

x == User 返回 true,但 case x 语句不运行与 User 关联的 block .这里发生了什么?

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:

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

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

但对于其他类型的对象,=== 可能有很多含义,完全取决于接收者。

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

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

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

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

对于 Procs,=== 实际上调用了那个 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/

关于Ruby `when' 关键字不在 case 语句中使用 ==。它有什么用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3757818/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com