map 使用 symbol 當引數的用法
※ 引述《suomax (shadow)》之銘言:
: arr = [1, 2, 3]
: arr.map(&to_s)
^^^^^ 是 &:to_s
: # => ["1", "2", "3"]
: arr.map(&class)
^^^^^^ 是 &:class
: # => [Fixnum, Fixnum, Fixnum]
: 大概可以看出這樣的語法等同於
: arr.map {|f| f.to_s} / arr.map {|f| f.class}
: 只是我不太懂為甚麼可以作這樣的 shortcut?
: 這是本來就有的功能,還是可以從語法的層面解釋呢?
→ suomax:自問自答 是因為 ActiveSupport 替 Symbol 加上 to_proc 09/01 01
這個答案的前提是你在 rails 裡面。
ruby 碰到 & 時,會把後面的東西當成 block 丟進去。
如果他是 Proc, 則直接進去,如果不是 Proc, 則試著呼叫 to_proc.
ActiveSupport 在 Symbol#to_proc 加上的東西是把第一 argument 當
message receiver, 其餘 arguments 當此 message 的 arguments.
意思就是 :to_s.to_proc['abc'] 跟 'abc'.to_s 的意思是一樣的。
除了 ActiveRecord 外,Ruby Facets 也有加上這個功能。
Ruby 1.8.7 也有,Ruby 1.9 也有,Rubinius 也有,JRuby 也有...
只有 MRI 1.8.6 和之前的版本沒有...
--
Nobody can take anything away from him.
Nor can anyone give anything to him.
What came from the sea,
has returned to the sea.
Chrono Cross
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 220.135.28.18
Ruby 近期熱門文章
PTT數位生活區 即時熱門文章