8
我想了解*(1..9)
和[*1..9]
瞭解紅寶石圖示
之間的區別,如果我把它們分配給變量,他們的工作方式相同
splat1 = *(1..9) # splat1 = [1, 2, 3, 4, 5, 6, 7, 8, 9]
splat2 = [*1..9] # splat2 = [1, 2, 3, 4, 5, 6, 7, 8, 9]
但事情變得奇怪,當我嘗試直接使用*(1..9)
和[*1..9]
。
*(1..9).map{|a| a.to_s} # syntax error, unexpected '\n', expecting tCOLON2 or '[' or '.'
[*1..9].map{|a| a.to_s} # ["1", "2", "3"...]
我猜是問題的一部分是與運營商precidence?但我不確定發生了什麼事。爲什麼我無法使用*(1..9)
我可以使用[*1..9]
?
'P *(1..9){.MAP | A | a.to_s}'工作正常 – Bohdan
同樣,'([* 1..9])map'應該做工精細。不過,我認爲明確的'to_a'方法更加清晰,基本上同樣簡潔。 – maerics