eachの戻り値について
eachの戻り値がわかってなかったので、備忘録で書いておきます。
fruits = %w(apple orange grape) def sample puts "hoge" puts yield puts "Hoge" end sample do fruits.each do |fruit| "I like #{fruit}" end end → hoge apple orange grape Hoge
I like
が入っていません。
原因は、eachの戻り値がfruit
で終わっているからです。
こういうことです。
def sample puts "hoge" puts fruits puts "Hoge" end
mapで展開後のものを返します。
fruits = %w(apple orange grape) def sample puts "hoge" puts yield puts "Hoge" end sample do fruits.map do |fruit| "I like #{fruit}" end end → hoge I like apple I like orange I like grape Hoge
戻り値の意識が足りてない・・・orz