Forum: Ruby How to Convert an Object into a Hash

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
55b646f35b70676d62dcca1763a66cef?d=identicon&s=25 Jason Vogel (Guest)
on 2007-02-02 07:45
(Received via mailing list)
I have an object (happens to be an ActiveRecord Model), but this is
not a Rails question.

params = { :contract_id => contract_payment['contract_id'], :amount =>
contract_payment['amount'] }

params = contract_payment.to_hash  # This is what I want to do...

I want to "automagically" convert the contract_payment object to a

I would really appreciate any help.

6076c22b65b36f5d75c30bdcfb2fda85?d=identicon&s=25 Ezra Zygmuntowicz (Guest)
on 2007-02-02 08:05
(Received via mailing list)
On Feb 1, 2007, at 10:45 PM, Jason Vogel wrote:

> I would really appreciate any help.
> Thanks,
> Jason

  Since you are using ActiveRecord you can already get the attributes



-- Ezra Zygmuntowicz
-- Lead Rails Evangelist
-- Engine Yard, Serious Rails Hosting
-- (866) 518-YARD (9273)
Cd3312ac93f768b1b449af457c0fca06?d=identicon&s=25 Daniel Finnie (Guest)
on 2007-02-02 08:06
(Received via mailing list)
I don't know how the internals of contract_payment's class is set up,
but you could do this in some cases:
daniel@daniel-desktop:~$ irb
 >> class Car
 >>   def initialize(color, make, model_year, owner)
 >>     @color, @make, @model_year, @owner = color, make, model_year,
 >>     end
 >>   end
=> nil
 >> myCar ="green", "Ford", 2007, "Me!")
=> #<Car:0xb7bd566c @color="green", @owner="Me!", @model_year=2007,
 >> myCar.instance_variables
=> ["@color", "@owner", "@model_year", "@make"]
 >> properties =
=> {}
 >> myCar.instance_variables.each {|x| properties[x[1..-1]] =
myCar.instance_variable_get(x) }
=> ["@color", "@owner", "@model_year", "@make"]
 >> properties
=> {"model_year"=>2007, "make"=>"Ford", "color"=>"green",
This topic is locked and can not be replied to.