-1

We have a class with attr_accessors. Such as:

class Class
  attr_accessor :x
  attr_accessor :y

  ...

end

I want to create a hash from an instance of this class. Such as:

c.to_attr_hash = { :x => "x", :y => "y" }

How could this be done?

Han Tuzun
  • 461
  • 1
  • 5
  • 9

1 Answers1

-1
class Class
  attr_accessor :x
  attr_accessor :y

  def to_attr_hash
    hash = Hash.new
    instance_variables.each do |v|
      hash[v] = instance_variable_get(v)
    end
    hash
  end
end

c = Class.new

c.x = 'a'
c.y = 'b'

p c.to_attr_hash

#=> {:@x=>"a", :@y=>"b"}
Eugene Yak
  • 334
  • 4
  • 11
  • A bit more concise (and more ruby like) solution would be: `instance_variables.each_with_object({}) { |var, hash| hash[var] = instance_variable_get(var) }` – Anthony Dec 01 '16 at 12:08
  • This lists the instance variables, not the `attr_accessor`s. By the way, monkey-patching core classes such as `Class` should only be done *veeeeery* carefully, and if there is really no other choice. – Jörg W Mittag Dec 02 '16 at 08:56
  • Try `c = Class.new; c.instance_variable_set(:@i_am_not_an_attr_accessor, 42); c.to_attr_hash`, and you will see that none of the two `attr_accessor`s show up whereas something which is *not* an `attr_accessor` *does* show up. – Jörg W Mittag Dec 02 '16 at 08:59