From: Logan Capaldo Date: 2006-07-08T14:11:05+09:00 Subject: Re: newbie Q - calling a method for an object in an .each block? On Jul 8, 2006, at 12:53 AM, william robb wrote: > Hello All. Sorry if this is obvious, but I have looked over the list > (and pickax) and not been able to solve it. > > I am trying to iterate over a collection of objects, calling a method > defined within each object. > > I have a class Card, with a method 'show' defined. > > I then create an array of these Card objects. For example: >> hand = Array.new >> ace = Card.new( some_parameters ) >> hand[0] = ace >> hand.push(Card.new( some_other_parameters)) > etc. > > Now, > >> ace.show #works: > =>"Card: A of Spades > hand[0].show # works, calls the 'show' method, executed for the first > 'card', the ace: > =>"Card: A of Spades" > > But, > >> hand.each {|c| c.show} # dosn't produces the following, which >> looks to me like a dump of the array: > =>[#, # @face="Up", @value=0, @suit="d">] > > I fear I am misunderstanding something fundamental here, as I thought > the block parameter c should get each element of the array in turn, > and, > each element being an object, I could call the methods associated with > that object. > > Thanks for any insight, > > Will > > > > -- > Posted via http://www.ruby-forum.com/. > It's working but #each returns the array and your #show method returns a string, it doesn't have any side effects. You may want to use map instead or use puts e.g.: hand.each { |c| puts c.show } or hand.map { |c| c.show }