LoginSignup
3
3

More than 5 years have passed since last update.

引数の value = Proc.new について

Posted at

以下の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
3
3
0

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
3
3