0

I have a method that gets artists top albums from Lastfm

    def get_albums
        @albums = Array.new
        @artistname.each do |name|
            s = LastFM::Artist.get_top_albums(:artist => name, :limit => 1)
            r = JSON.parse(s.to_json)['topalbums']['album']['name']
            @albums.push r                      
            end
    end

This method work fine and returns an array of albums for each artist as long as the artist has a top album, if they don't I get a NoMethodError undefined method `[]' for nil:NilClass.

What I'm trying to do is add a check when parsing to try and get pass this NoMethodError but can't seem to figure it out. I tried this:

    def get_albums
        @albums = Array.new
        @artistname.each do |name|
            s = LastFM::Artist.get_top_albums(:artist => name, :limit => 1)
            r = JSON.parse(s.to_json)['topalbums']['album']['name']
            if['topalbums']['album']['name'].empty?
                @albums.push(@artistname + "does not have a top album")
            else
                @albums.push r                      
            end
                end

    end

Which gives me a TypeError can't convert String into Integer message

Any ideas how I could fix this? Thanks

0

1 Answer 1

0

The + operator is not a concat operator in ruby.

What you are attempting to use is the << operator.

@albums.push(@artistname << " does not have a top album")
Sign up to request clarification or add additional context in comments.

7 Comments

Cheers I've changed the + to << but I'm still getting the TypeError cannot convert String to integer on this line of code if['topalbums']['album']['name'].empty?
Are you actually getting the error on this line of code?
Also, if['topalbums']['album']['name'].empty? doesn't make any sense. You need to specify the hash that you are searching through.
Change that to if r.empty?
Tried that but getting undefined method `[]' for nil:NilClass for r = JSON.parse(s.to_json)['topalbums']['album']['name']
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.