以下のActiveRecordのselectメソッドの実装の、引数「value = Proc.new」がよくわからなかったのでメモ。
selectメソッドの利用
User.where('id < 100').select(&->(user) {user.created_at > Date.new(2013, 1, 1)})
selectメソッドの実装
def select(value = Proc.new)
if block_given?
to_a.select {|*block_args| value.call(*block_args) }
else
relation = clone
relation.select_values += Array.wrap(value)
relation
end
end
リファレンスに以下のような例が載ってあった。
http://docs.ruby-lang.org/ja/2.1.0/class/Proc.html
def foo
pr = Proc.new
pr.call(1)
end
foo {|arg| p arg }
# => 1
ということで、Arrayのmapで試してみた。
class Array
def wrap_map(value = Proc.new)
map {|element| value.call(element * 2)}
end
end
[1, 2, 3].wrap_map(&:to_s)
# => ["2", "4", "6"]
[1, 2, 3].wrap_map {|v| v * 2}
# => [4, 8, 12]
ちなみに以下でも同じ
class Array
def wrap_map(&value) # こう書いてもOK
map {|element| value.call(element * 2)}
end
end