Dynamic class instantiation by iteration

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.

On Wednesday 30 April 2008, Frisco Del R. wrote:

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

Hi –

On Wed, 30 Apr 2008, Stefano C. wrote:

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) :slight_smile:

David

On Wednesday 30 April 2008, David A. Black wrote:

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

Make that Cat.new(n) :slight_smile:

Of course

Stefano

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

David A. Black wrote:

|
| Make that Cat.new(n) :slight_smile:

Hm. Shouldn’t that be Cat.mew(n)? :stuck_out_tongue:

SCNR.


Phillip G.
Twitter: twitter.com/cynicalryan
Blog: http://justarubyist.blogspot.com

You watch a talk show recently? They’re doing one next month on a
normal, happy heterosexual couple, assuming they can find one.
~ – Professor Ralph Noble, RPI, Psychology of Motivation, Fall 1991
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.8 (MingW32)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org

iEYEARECAAYFAkgYguAACgkQbtAgaoJTgL+7XQCfcoRXtIQAowRjrAeQtgdxjOQX
Q0oAoJ9RuAnFK6bhdXWjMi5NTwIpnVhV
=D5D5
-----END PGP SIGNATURE-----