LoginSignup
2
1

More than 5 years have passed since last update.

rubyのinjectをcoolに書く方法

Last updated at Posted at 2018-01-30

この二つは同じ

[1,2,3].inject(5){|init, v| init + v}
[1,2,3].inject(5, &:+)

追記;これも同じ

[1,2,3].inject(5, :+)
block、proc、&の説明

& operator to convert a symbol to a Proc and then to a block:

names = ['bob', 'bill', 'heather']
//これは全て同じ結果
names.map {|name| name.capitalize } 
names.map(&:capitalize.to_proc)
names.map(&:capitalize)

to_procは何をやっているのか?

class Symbol
  def to_proc
    Proc.new {|x| x.send(self) }
  end
end
2
1
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1