clone method in ruby
My project had a requirement where the database table had the records of the type -
attr1 => a<>b<>c
attr2 => 1<>2<>3
id => 2
The data is stored in a legacy system and in a non normalized format - probably for performance :)
or who knows why ?
But it essentially means that a in attr1 is mapped to 1 from att2
i.e -
a <=> 1
b <=> 2
c <=> 3
This record thus stores information of 3 records merged into a single record.
The best way to split records is with clone function. It indeed saved my day after spending a lot of time trying to split the records or just create copies of the records...
Here is what I was trying -
model = Model.first
o1 = model #to hold a <=> 1
o2 = model #to hold b <=> 2
o3 = model #to hold c <=> 3
To my annoyance, o1,o2,o3 all referred to the same model object in memory... :)
Then came clone() to help me write the following code -
o1 = model.clone #to hold a <=> 1
o2 = model.clone #to hold b <=> 2
o3 = model.clone #to hold c <=> 3
Getting to learn about all OO fun !!!
Reference -
http://www.ruby-doc.org/core/classes/Object.html#M000349
Thursday, April 16, 2009
Subscribe to:
Post Comments (Atom)
0 comments:
Post a Comment