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

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

More than 1 year has passed since last update.

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
wai-doi
Ruby / Rails / Agile / 自然言語処理 /
esm
We build applications which work well and make customers happy.
http://www.esm.co.jp
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.
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
ユーザーは見つかりませんでした