I have a Ruby class. I want to get an instance variable from an argument to a method in that class. I can do get all of the instance variables as an array:
self.instance_variables
However, I want to get the instanc开发者_如何学运维e variable named arg
, specifically:
class MyClass
def get_instance_variable(arg)
hash_of_instance_variables[arg]
end
end
object.get_instance_variable('my_instance_var')
How do I compute hash_of_instance_variables
?
To create a hash of all instance variables you can use the following code:
class Object
def instance_variables_hash
Hash[instance_variables.map { |name| [name, instance_variable_get(name)] } ]
end
end
But as cam mentioned in his comment, you should use instance_variable_get
method instead:
object.instance_variable_get :@my_instance_var
Question is quite old but found rails solution for this: instance_values
This is first answer in google so maybe it will help someone.
class MyClass
def variables_to_hash
h = {}
instance_variables.each{|a|
s = a.to_s
n = s[1..s.size]
v = instance_variable_get a
h[n] = v
}
h
end
end
For Ruby 2.6+, you can pass a block to the to_h
method, leading to very DRY syntax:
# Some instance variables
instance_variable_set(:@a, 'dog')
#=> "dog"
instance_variable_set(:@b, 'cat')
#=> "cat"
# Array of instance variable names
instance_variables
#=> [:@a, :@b]
# Hash of instance variable names and values, including leading @
instance_variables.to_h { |k| [k, instance_variable_get(k)] }
#=> { :@a => "dog", :@b => "cat" }
# Hash of instance variable names and values, excluding leading @
instance_variables.to_h { |k| [k[1..-1].to_sym, instance_variable_get(k)] }
#=> { :a => "dog", :b => "cat" }
Ruby on Rails has a couple of built-in ways to do this that you might find meet your needs.
user = User.new(first: 'brian', last: 'case')
- attributes (Rails API: ActiveModel::AttributeMethods)
user.attributes
{"first"=>"brian", "last"=>"case"}
- serializable_hash (Rails API: Active Model Serialization)
user.serializeable_hash
{"first"=>"brian", "last"=>"case"}
精彩评论