Philip Mak wrote:
> >>     person = {
> >>         :name => "John Doe",
> >>         :age => 20
> >>     }
> >
> > But wouldn't write code like the above. I would create a class
> > "Person" instead. Hashes with a fixed set of keys are almost
> > screaming for you to create a new class.
> 
> I've thought of doing that, but I found certain properties of the hash
> to be convenient. For example, Hash#keys will tell me the name of all
> the fields inside the hash. Then, if I have a "person" object as
> defined above, storing it into SQL is pretty simple:
> 
> (code not tested, but should be more or less right)
> 
> def insert(table, hash)
>     Db.do "INSERT INTO #{table} SET #{
>         #{hash}.to_a.collect {
>             |key, value| "#{key} = #{Mysql.quote(value)}"
>         }.join(", ")
>     }"
> end
> 
> insert('person', person)

You can get the names of all instance variables of an object with
obj.instance_variables, so you could write something similar to the
above.
If you have everything in a Person class you can also let that class
know about the table structure the instances are stored in, so the
objects can store themselves even.

/Anders

-- 

A n d e r s  B e n g t s s o n  |  ndrsbngtssn / yahoo.se
Stockholm, Sweden               |

_____________________________________________________
F?lj VM p? n?ra h?ll p? Yahoo!s officielle VM-sajt www.yahoo.se/vm2002
H?ll dig ajour med nyheter och resultat, med vinnare och f?rlorare...