Help us understand the problem. What is going on with this article?

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

More than 3 years have passed since last update.

以下の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
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away