Definning "to_s" in a class - inexpected result

  • Thread starter Andrés Suárez
  • Start date
A

Andrés Suárez

Hi,

I'm trying to obtain the cards of a Deck in a string like
"2s...KsAs2h...Ah2d...Ad2c...Ac". The problem with the folowing code is
that in the end of the string appears "#<Deck:0x2bb5880>". Why? Can I
avoid it?

class Deck

SUITS = %w{s d h c}
RANKS = %w{2 3 4 5 6 7 8 9 T J Q K A}

def initialize
@cards = []
SUITS.each{ |s| RANKS.each{ |r| @cards << r+s } }
end

def popCard
@cards.pop
end

def to_s
@cards.map{ |card| print card}
end

end

d0 = Deck.new
puts d0


Regards,
Andrés
 
S

Sebastian Hungerecker

Andr=C3=A9s Su=C3=A1rez said:
def to_s
=C2=A0 [email protected]{ |card| print card}
=C2=A0 end

to_s needs to return a string otherwise puts will not use it. Your to_s=20
returns an array (as map returns an array) - an array of nils to be precise=
=20
(because print returns nil).
Also to_s should not print anything to the screen.

HTH,
Sebastian
=2D-=20
NP: Depeche Mode - Barrel Of A Gun
Jabber: (e-mail address removed)
ICQ: 205544826
 
S

Stefano Crocco

Hi,

I'm trying to obtain the cards of a Deck in a string like
"2s...KsAs2h...Ah2d...Ad2c...Ac". The problem with the folowing code is
that in the end of the string appears "#<Deck:0x2bb5880>". Why? Can I
avoid it?

class Deck

SUITS =3D %w{s d h c}
RANKS =3D %w{2 3 4 5 6 7 8 9 T J Q K A}

def initialize
@cards =3D []
SUITS.each{ |s| RANKS.each{ |r| @cards << r+s } }
end

def popCard
@cards.pop
end

def to_s
@cards.map{ |card| print card}
end

end

d0 =3D Deck.new
puts d0


Regards,
Andr=C3=A9s

There are two problems with your code. The first is the use of print in the=
=20
to_s method. print displays its arguments on screen and returns nil. So, th=
e=20
return value of the @cards.map expression is an array filled with nil=20
elements. The second problem lies in the fact that your to_s method returns=
an=20
array.

You can solve both problems using the following definition of Deck#to_s:

def to_s
@cards.join ' '
end

Since the elements of the @cards array are already strings, you don't need =
to=20
convert them. Instead, you have to convert the array itself to a string: us=
ing=20
join will convert each element of the array to a string, then concatenates=
=20
them inserting a space between each pair.

I hope this helps

Stefano
 
R

Robert Dober

On Sat, Jun 14, 2008 at 9:06 PM, Sebastian Hungerecker
You dealt nice with this Sebastian ;)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,961
Messages
2,570,131
Members
46,689
Latest member
liammiller

Latest Threads

Top