Skip to content

Instantly share code, notes, and snippets.

@kisai
Created September 12, 2014 18:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kisai/f2459abfff7381883674 to your computer and use it in GitHub Desktop.
Save kisai/f2459abfff7381883674 to your computer and use it in GitHub Desktop.
Convert object to hash in ruby
class Gift
def initialize
@name = "book"
@price = 15.95
end
end
gift = Gift.new
hash = {}
gift.instance_variables.each {|var| hash[var.to_s.delete("@")] = gift.instance_variable_get(var) }
p hash # => {"name"=>"book", "price"=>15.95}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment