[lnkForumImage]
TotalShareware - Download Free Software

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


 

Forums >

comp.lang.ruby

Convert one object to another

Tim Hunter

12/20/2004 4:22:00 PM

I have two objects, big and little. I need to convert big to little. Big and
little don't have much in common except little's instance variables are a
subset of big's. That is, to convert big to little I need to copy the
instance variables they have in common. What's the right way to do this?
Should I add a "to_little" instance method to big's class, or should I add
a "from_big" singleton method to little's class? Neither one seems right.
3 Answers

Eric Anderson

12/20/2004 5:22:00 PM

0

Tim Hunter wrote:
> I have two objects, big and little. I need to convert big to little. Big and
> little don't have much in common except little's instance variables are a
> subset of big's. That is, to convert big to little I need to copy the
> instance variables they have in common. What's the right way to do this?
> Should I add a "to_little" instance method to big's class, or should I add
> a "from_big" singleton method to little's class? Neither one seems right.

You could do both (TIMTOWTDI) but I would lean towards to_little. It
matches the existing Ruby library. For example the to_s() methods, or
the String object's to_i() method. I think there are also to_a() for
converting to arrays in some objects.

Just my 2 cents,

Eric

Robert Klemme

12/20/2004 5:27:00 PM

0


"Eric Anderson" <eric@afaik.us> schrieb im Newsbeitrag
news:32og2lF3olcvuU1@individual.net...
> Tim Hunter wrote:
> > I have two objects, big and little. I need to convert big to little.
Big and
> > little don't have much in common except little's instance variables
are a
> > subset of big's. That is, to convert big to little I need to copy the
> > instance variables they have in common. What's the right way to do
this?
> > Should I add a "to_little" instance method to big's class, or should I
add
> > a "from_big" singleton method to little's class? Neither one seems
right.
>
> You could do both (TIMTOWTDI) but I would lean towards to_little. It
> matches the existing Ruby library. For example the to_s() methods, or
> the String object's to_i() method. I think there are also to_a() for
> converting to arrays in some objects.
>
> Just my 2 cents,

+1 for to_little. Could look like this

class Little
end

class Big
def to_little
little = Little.allocate

%w{@inst_var1 @inst_var2}.each do |iv|
little.instance_variable_set(iv, instance_variable_get(iv))
end

little
end
end

Kind regards

robert

Tim Hunter

12/20/2004 8:39:00 PM

0

Robert Klemme wrote:
>
> +1 for to_little. Could look like this
>
That's the approach I had in mind. Thanks for validating it!