Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
3
Help us understand the problem. What is going on with this article?
@shshimamo

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

More than 5 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
3
Help us understand the problem. What is going on with this article?
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

No comments
Sign up for free and join this conversation.
Sign Up
If you already have a Qiita account Login
3
Help us understand the problem. What is going on with this article?