Definning "to_s" in a class - inexpected result

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

Andrés Suárez wrote:

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

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

HTH,
Sebastian

On Saturday 14 June 2008, Andrés Suárez wrote:

RANKS = %w{2 3 4 5 6 7 8 9 T J Q K A}
def to_s
Andrés
There are two problems with your code. The first is the use of print in
the
to_s method. print displays its arguments on screen and returns nil. So,
the
return value of the @cards.map expression is an array filled with nil
elements. The second problem lies in the fact that your to_s method
returns an
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
convert them. Instead, you have to convert the array itself to a string:
using
join will convert each element of the array to a string, then
concatenates
them inserting a space between each pair.

I hope this helps

Stefano

On Sat, Jun 14, 2008 at 9:06 PM, Sebastian H.
[email protected] wrote:
You dealt nice with this Sebastian :wink:

Thanks for the replies!

Now I understand better “print” and “to_s”.

:smiley: