4
我剛纔注意到Array沒有覆蓋三重等號方法===
,它有時被稱爲case平等方法。爲什麼數組不會覆蓋Ruby中的三重等號方法?
x = 2
case x
when [1, 2, 3] then "match"
else "no match"
end # => "no match"
而範圍符不:
x = 2
case x
when 1..3 then "match"
else "no match"
end # => "match"
可以爲數組做一個解決方法,但是:
x = 2
case x
when *[1, 2, 3] then "match"
else "no match"
end # => "match"
難道知道爲什麼是這樣?
難道是因爲它更可能是x
是一個實際的數組而不是一個範圍,而數組覆蓋===
意味着普通的等式不會匹配?
# This is ok, because x being 1..3 is a very unlikely event
# But if this behavior occurred with arrays, chaos would ensue?
x = 1..3
case x
when 1..3 then "match"
else "no match"
end # => "no match"
你的直覺相匹配礦。我想不出有很多場景想要將Range傳遞給'case'表達式以使其與其他範圍匹配,但我可以想到幾個你要傳遞一個Array來查看它完全匹配另一個數組。 –
你可能不得不問核心的一個明確的答案。我的猜測是數組的行爲不像*,因爲*範圍。 – sheldonh