I’m a noob, trying to learn ruby.
I’m following along with the book Programming Ruby, The Pragmatic
Programmer’s Guide, which comes with ruby documentation.
Im on chapter, Implementing a SongList Container, doing the code
samples, but i’m getting the following error when trying to run the
code:
18:in append': undefined methodpush’ for nil:NilClass
(NoMethodError)
from F:/InstantRails/rails_apps/test/test2.rb:80
I have a SongList class with the following method:
def append(aSong) @songs.push(aSong)
self
end
and im trying to run the code sample as in the book:
yes that was the problem.I just typed initialize incorrectly, so my
array was not being initialized.I should’ve got a decent ide to avoid
this stupid mistakes.
Thanks
|
|list.
| append(Song.new(‘title1’, ‘artist1’, 1)).
| append(Song.new(‘title2’, ‘artist2’, 2)).
| append(Song.new(‘title3’, ‘artist3’, 3)).
| append(Song.new(‘title4’, ‘artist4’, 4))
|
|This doesnt make any sense. I can create the Song object just fine,
|but if i try to add it to the array i get this erro.
|Can anyone help me please?
What do you have in the initialize method of the SongList class? From
the
error message you get, it seems that @songs is nil instead of being an
array.
To avoid this, you need to set the @songs instance variable to an array
and
usually this is done in the initialize method. It should be something
like
this:
class SongList
def initialize #other initialization code can go here @songs = [] #other initialization code can go here
end
end
I hope this helps
Stefano
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.