[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

How to Convert an Object into a Hash

Jason Vogel

2/2/2007 6:44:00 AM

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
hash.

I would really appreciate any help.

Thanks,
Jason

2 Answers

Ezra Zygmuntowicz

2/2/2007 7:05:00 AM

0


On Feb 1, 2007, at 10:45 PM, Jason Vogel wrote:

> 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
> hash.
>
> I would really appreciate any help.
>
> Thanks,
> Jason
>
>


Since you are using ActiveRecord you can already get the attributes
hash:

contract_payment.attributes

Cheers-

-- Ezra Zygmuntowicz
-- Lead Rails Evangelist
-- ez@engineyard.com
-- Engine Yard, Serious Rails Hosting
-- (866) 518-YARD (9273)



Daniel Finnie

2/2/2007 7:07:00 AM

0

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, owner
>> end
>> end
=> nil
>> myCar = Car.new("green", "Ford", 2007, "Me!")
=> #<Car:0xb7bd566c @color="green", @owner="Me!", @model_year=2007,
@make="Ford">
>> myCar.instance_variables
=> ["@color", "@owner", "@model_year", "@make"]
>> properties = Hash.new
=> {}
>> 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", "owner"=>"Me!"}
>>


Jason Vogel wrote:
> 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
> hash.
>
> I would really appreciate any help.
>
> Thanks,
> Jason
>
>
>