LoginSignup
126
121

More than 5 years have passed since last update.

Rubyでオブジェクトの中身を調べたい時によく使うメソッド

Posted at

Rubyでオブジェクトの中身を調べたい時によく使うメソッド

Rubyはクラスの定義やメソッドの定義の情報を実行時に持っているので、
pry などを使用してオブジェクトが今どういう状態なのか簡単に確認できる。
知っておくと便利な確認方法をメモとしてあげておく。

テスト用のコード

class Sample
   @val = ""
   @@val2 = "class_variable"

   def initialize
     @val = "instance_variable"
   end

   def show
     puts @val
   end
end

sample = Sample.new

インスタンス変数一覧を取得したい

インスタンスオブジェクトから、一覧が取得できる。

[5] pry(main)> sample.instance_variables
=> [:@val]

クラス変数一覧を取得したい

クラス変数はクラスオブジェクトから取得する。

[6] pry(main)> Sample.class_variables
=> [:@@val2]
[7] pry(main)> sample.class.class_variables
=> [:@@val2]

インスタンスメソッド一覧を取得したい

メソッドの情報は、インスタンスオブジェクトではなく、クラスオブジェクトが情報を持っているので、
こちらから呼び出す。

[9] pry(main)> Sample.instance_methods(false)
=> [:show]

引数に与えるbool値をfalseにすると、そのクラスで定義されたメソッドのみを出力し、
trueなら親から継承したメソッドも含めて返す。

出力が大量にあるときは、以下のようにgrepを使うと便利。

[15] pry(main)> Sample.instance_methods(true).grep(/^to/)
=> [:to_json, :to_yaml, :to_yaml_properties, :to_param, :to_query, :to_enum, :to_s]

method_missingが定義されているクラスの場合、メソッド一覧にないものでも、何かしら使用されている場合があるので、注意が必要。

クラスの親、祖先が知りたい

Module#ancestors を使う。

[27] pry(main)> Sample.ancestors
=> [Sample,
 ActiveSupport::ToJsonWithActiveSupportEncoder,
 Object,
 PP::ObjectMixin,
 ActiveSupport::Dependencies::Loadable,
 JSON::Ext::Generator::GeneratorMethods::Object,
 ActiveSupport::Tryable,
 Kernel,
 BasicObject]

メソッドの定義されている場所、内容が知りたい

Methodオブジェクトのsource_locationを使えば、メソッドが定義されている場所と行数が得られる。

23] pry(main)> 1.method(:to_s).source_location
=> ["..(略)/gems/activesupport-5.0.0/lib/active_support/core_ext/numeric/conversions.rb", 103]

pryを使っているなら、以下のようにコメントと定義を得ることができて便利。

[26] pry(main)> ? 1.to_s
 # コメントを表示・・・
[27] pry(main)> $ 1.to_s
 # ソースを表示・・・

他にも色々あるけど、とりあえずよく使いそうなのは以上。
また適宜追予定。

126
121
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
126
121