4
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

pryでメソッド定義をすぐ見つける方法

Posted at

こちらの記事にコメントを残されていた方のrubyのメソッド定義を見つける方法がかなり楽だったので共有させていただきます。

pry gemを入れてるのが前提です。

? reciever.method => メソッドのドキュメント表示

map はc言語で実装されてるらしい

[1] pry(main)> ? [1,2,3].map

From: array.c (C Method):
Owner: Array
Visibility: public
Signature: map()
Number of lines: 9

Invokes block once for each element of self. Creates a
new array containing the values returned by the block.
See also Enumerable#collect.

If no block is given, an enumerator is returned instead.

   a = [ "a", "b", "c", "d" ]
   a.collect {|x| x + "!" }   #=> ["a!", "b!", "c!", "d!"]
   a                          #=> ["a", "b", "c", "d"]

presence は便利メソッドがいっぱいあるgemactivesupportで定義されている。
説明もわかりやすい。

[2] pry(main)> ? "".presence

From: /$HOME/.rbenv/versions/2.4.0/lib/ruby/gems/2.4.0/gems/activesupport-5.1.4/lib/active_support/core_ext/object/blank.rb @ line 27:
Owner: Object
Visibility: public
Signature: presence()
Number of lines: 16

Returns the receiver if it's present otherwise returns nil.
object.presence is equivalent to

   object.present? ? object : nil

For example, something like

  state   = params[:state]   if params[:state].present?
  country = params[:country] if params[:country].present?
  region  = state || country || 'US'

becomes

  region = params[:state].presence || params[:country].presence || 'US'

return [Object]

$ reciever.method => メソッドのソースコード表示

さっき見た通りc言語で実装されているmapメソッド

[3] pry(main)> $ [1,2,3].map

From: array.c (C Method):
Owner: Array
Visibility: public
Number of lines: 13

static VALUE
rb_ary_collect(VALUE ary)
{
    long i;
    VALUE collect;

    RETURN_ENUMERATOR(ary, 0, 0);
    collect = rb_ary_new2(RARRAY_LEN(ary));
    for (i = 0; i < RARRAY_LEN(ary); i++) {
    rb_ary_push(collect, rb_yield(RARRAY_PTR(ary)[i]));
    }
    return collect;
}

presence もしっかり定義されている

[4] pry(main)> $ "".presence

From: /$HOME/.rbenv/versions/2.4.0/lib/ruby/gems/2.4.0/gems/activesupport-5.1.4/lib/active_support/core_ext/object/blank.rb @ line 43:
Owner: Object
Visibility: public
Number of lines: 3

def presence
  self if present?
end
4
2
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
4
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?