17
11

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.

[Ruby]インスタンス変数名とその値をハッシュで取得する

Last updated at Posted at 2018-01-18

instance_variables_and_valuesは引数で与えられたインスタンスについて、定義されたインスタンス変数名とその値をハッシュで取得するメソッドです。

class User
  def initialize(name, age)
    @name = name
    @age = age
  end
end

def instance_variables_and_values(instance)
  instance
    .instance_variables
    .map{ |sym| [sym, instance.instance_variable_get(sym)] }
    .to_h
end

taro = User.new('Taro', 20)
puts instance_variables_and_values(taro)
#=> {:@name=>"Taro", :@age=>20}

使ったメソッド

instance_variables

レシーバが持つ定義されたインスタンス変数名をシンボルの配列で返す

class User
  def initialize(name, age)
    @name = name
    @age = age
  end
end

taro = User.new('Taro', 20)
taro.instance_variables #=> [:@name, :@age]

instance_variable_get

レシーバが持つインスタンス変数の値を返す。引数にはインスタンス変数名をシンボルで与える

class User
  def initialize(name, age)
    @name = name
    @age = age
  end
end

taro = User.new('Taro', 20)
taro.instance_variable_get(:@name) #=> "Taro"
taro.instance_variable_get(:@age) #=> 20
17
11
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
17
11

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?