In Ruby, how can I get instance variables in a hash instead of an array?

天大地大妈咪最大 提交于 2019-11-29 04:03:42
Yossi

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

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')

user.attributes

{"first"=>"brian", "last"=>"case"}

user.serializeable_hash

{"first"=>"brian", "last"=>"case"}

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!