Finding an Album's Artist with the Spotify API

407 views Asked by At

I'm trying to use the rails gem for the Spotify API to find the artist(s) of a particular album. I would start by retrieving the name of the album as such:

album_results = RSpotify::Album.search("The Eminem Show")

To find the artist of that album I issued the following method to the variable above:

album_results.artists

This returns a ton of data I don't need. All I want is the name of the artist. I was able to accomplish this partially by doing:

album_results.first.artists.first.name
=> "Eminem"

What I'd like it to do is return the name all of the available artists for all album results. I tried using the select method but once again got too much data for what I wanted:

album_results.select {|album| album.artists}

What would be the best approach to accomplish this?

1

There are 1 answers

1
Siva On BEST ANSWER

Using select here will return all the records with artists.

You need to use either collect or map

my_artists = album_results.flat_map{ |album| 
  album.artists.collect{|artist| artist.name}
}

EDIT

Use flat_map which returns a flattened array by default.

More efficient than using collect and flatten!