工作,我覺得在這的Ruby代碼是相當有趣的如何 「(1..4).inject(:+)」 在Ruby中
(1..4).inject(&:+)
好吧,我知道什麼inject
呢,我知道這個代碼基本上相當於
(1..4).inject(0) {|a,n| a + n}
但它究竟如何工作?
爲什麼&:+
相同寫入塊{|a,n| a + n}
?
爲什麼它不需要初始值?我確定與inicial值爲0,但(1..4).inject(&:*)
也適用,並且有初始值必須是1 ...
這真是兩個完全不同的問題,其中第一個的是,其上已經不下11個其他問題重複問及在這裏找到答案在計算器上:http://StackOverflow.Com/q/99318/ http://StackOverflow.Com/q/1217088/ http://StackOverflow.Com/q/1792683/ http://StackOverflow.Com/q/1961030/http://StackOverflow.Com/q/2096975/ http://StackOverflow.Com/q/2211751/ http://StackOverflow.Com/q/2259775/ http://StackOverflow.Com/q/2388337/http://StackOverflow.Com/q/2697024/ http://StackOverflow.Com/q/3888044/ http://StackOverflow.Com/q/4512587/ – 2011-02-15 18:46:50