[lnkForumImage]
TotalShareware - Download Free Software

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


 

Forums >

comp.lang.ruby

Dynamic class instantiation by iteration

Frisco Del Rosario

4/30/2008 7:17:00 AM

I'm curious as to why the following does not create three instances of
class Cat:


class Cat
def initialize(name)
@name = name
end
end

toons = ["Felix", "Garfield", "Heathcliff"]

toons.each {|t| t = Cat.new(t)}


In irb, the last input and output are:

irb(main):008:0> toons.each {|t| t=Cat.new(t)}
=> ["Felix", "Garfield", "Heathcliff"]

which I don't understand.
3 Answers

Stefano Crocco

4/30/2008 7:23:00 AM

0

On Wednesday 30 April 2008, Frisco Del Rosario wrote:
> I'm curious as to why the following does not create three instances of
> class Cat:
>
>
> class Cat
> def initialize(name)
> @name = name
> end
> end
>
> toons = ["Felix", "Garfield", "Heathcliff"]
>
> toons.each {|t| t = Cat.new(t)}
>
>
> In irb, the last input and output are:
>
> irb(main):008:0> toons.each {|t| t=Cat.new(t)}
> => ["Felix", "Garfield", "Heathcliff"]
>
> which I don't understand.

Your code does create three instances of Cat, but they're thrown away
immediately, since you don't use them. Array#each always return the receiver
(in your case, the array ["Felix", "Garfield", "Heathcliff"]), regardless of
the return value of the block. If you want to obtain an array with the three
instances of Cat, use Array#map instead:

cats = toons.map{|n| Cat.new(name)}

I hope this helps

Stefano

David A. Black

4/30/2008 11:19:00 AM

0

Hi --

On Wed, 30 Apr 2008, Stefano Crocco wrote:

> On Wednesday 30 April 2008, Frisco Del Rosario wrote:
>> I'm curious as to why the following does not create three instances of
>> class Cat:
>>
>>
>> class Cat
>> def initialize(name)
>> @name = name
>> end
>> end
>>
>> toons = ["Felix", "Garfield", "Heathcliff"]
>>
>> toons.each {|t| t = Cat.new(t)}
>>
>>
>> In irb, the last input and output are:
>>
>> irb(main):008:0> toons.each {|t| t=Cat.new(t)}
>> => ["Felix", "Garfield", "Heathcliff"]
>>
>> which I don't understand.
>
> Your code does create three instances of Cat, but they're thrown away
> immediately, since you don't use them. Array#each always return the receiver
> (in your case, the array ["Felix", "Garfield", "Heathcliff"]), regardless of
> the return value of the block. If you want to obtain an array with the three
> instances of Cat, use Array#map instead:
>
> cats = toons.map{|n| Cat.new(name)}

Make that Cat.new(n) :-)


David

--
Rails training from David A. Black and Ruby Power and Light:
INTRO TO RAILS June 9-12 Berlin
ADVANCING WITH RAILS June 16-19 Berlin
INTRO TO RAILS June 24-27 London (Skills Matter)
See http://www.r... for details and updates!

Stefano Crocco

4/30/2008 2:18:00 PM

0

On Wednesday 30 April 2008, David A. Black wrote:
> > cats = toons.map{|n| Cat.new(name)}
>
> Make that Cat.new(n) :-)


Of course

Stefano