2011-10-12 30 views
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" 
+0

你的直覺相匹配礦。我想不出有很多場景想要將Range傳遞給'case'表達式以使其與其他範圍匹配,但我可以想到幾個你要傳遞一個Array來查看它完全匹配另一個數組。 –

+0

你可能不得不問核心的一個明確的答案。我的猜測是數組的行爲不像*,因爲*範圍。 – sheldonh

回答

2

因爲這是in the specification

it "treats a literal array as its own when argument, rather than a list of arguments" 

was added 2009年2月3日由Charles Nutter@headius)的規範。既然這個答案可能不是你要找的,你爲什麼不問他呢?

要在黑暗中採取狂野且完全不知情的刺法,在我看來,您可能已經在您的問題中使用了a splat來回答問題。由於該功能可以通過設計獲得,爲什麼在重複時會刪除測試Array相等的功能?如上面Jordan指出的那樣,在這種情況下有用的情況存在。


未來的讀者應該注意的是,除非有問題的陣列已經被實例化,使用數組都沒有必要以匹配多個表達式:

x = 2 

case x 
    when 1, 2, 3 then "match" 
    else "no match" 
end # => "match" 
相關問題