From: reavey Date: 2003-02-19T20:57:35+09:00 Subject: Re: help: append error on Array push --------------070004070704000705040204 Content-Type: text/plain; charset=us-ascii; format=flowed Content-Transfer-Encoding: 7bit Thanks for you help re-v Matt Armstrong wrote: >reavey writes: > > > >>I get an error >>"NameError: undefined method 'push' for nil from append" >>as I'm working thru the Prag prog ruby book. >>"""We'll start our class with a basic initialize method, which creates >>the Array we'll use to hold our songs and store a reference to it in >>the instance variable @songs >> >>class SongList >> def initialize >> @songs = Array.new >> end >> def append(aSong) >> @songs.push(aSong) >> self >> end >>end >> >>list = SongList.new >>list. >> append(Song.new('title1', 'artist1', 1)). >> append(Song.new('title2', 'artist2', 2)) """ >> >> > >The code you posted simply shouldn't report that error. Here is my >IRB session: > >irb(main):001:0> class SongList >irb(main):002:1> def initialize >irb(main):003:2> @songs = [] >irb(main):004:2> end >irb(main):005:1> def append(song) >irb(main):006:2> @songs.push(song) >irb(main):007:2> self >irb(main):008:2> end >irb(main):009:1> end >=> nil >irb(main):010:0> list = SongList.new >=> # >irb(main):011:0> list.append("foo").append("bar") >=> # > >P.S. for this test it doesn't matter what objects you pass to >SongList#append, since it just appends it to the @songs array. > > > --------------070004070704000705040204 Content-Type: text/html; charset=us-ascii Content-Transfer-Encoding: 7bit Thanks for you help
re-v

Matt Armstrong wrote:
reavey <reavey@nep.net> writes:

  
I get an error
"NameError: undefined method 'push' for nil from append"
as I'm working thru the Prag prog ruby book.
"""We'll start our class with a basic initialize method, which creates
the Array we'll use to hold our songs and store a reference to it in
the instance variable @songs

class SongList
    def initialize
      @songs = Array.new
    end
    def append(aSong)
        @songs.push(aSong)
        self
    end
end

list = SongList.new
list.
    append(Song.new('title1', 'artist1', 1)).
    append(Song.new('title2', 'artist2', 2))      """
    

The code you posted simply shouldn't report that error.  Here is my
IRB session:

irb(main):001:0> class SongList
irb(main):002:1> def initialize
irb(main):003:2> @songs = []
irb(main):004:2> end
irb(main):005:1> def append(song)
irb(main):006:2> @songs.push(song)
irb(main):007:2> self
irb(main):008:2> end
irb(main):009:1> end
=> nil
irb(main):010:0> list = SongList.new
=> #<SongList:0x401c4c10 @songs=[]>
irb(main):011:0> list.append("foo").append("bar")
=> #<SongList:0x401c4c10 @songs=["foo", "bar"]>

P.S. for this test it doesn't matter what objects you pass to
SongList#append, since it just appends it to the @songs array.

  

--------------070004070704000705040204--