dajwill / musicApp

Combined playlist creation pulling from Spotify and SoundCloud APIs
0 stars 0 forks source link

Working with RSpotify array #1

Open dajwill opened 9 years ago

dajwill commented 9 years ago

@chrisvfritz

I am trying to get top tracks of a searched artist. I was messing around in the console trying to create a loop that would return the name of every song in the top tracks array:

artist = RSpotify::Artist.search('Frank Ocean').first songs = artist.top_tracks(:US) songs.each do |s| s.name end

But instead of returning an array of track names it returns the same array as artist.top_tracks(:US), which is an incredibly long array of all the info on each track.

Do you know how to fix this?

chrisvfritz commented 9 years ago

I think what you want is:

song_names = songs.map do |s|
  s.name
end

map actually creates a new array where each item in the array is replaced by the last line in the block (the do...end). Let me know if that's what you were looking for!

dajwill commented 9 years ago

Thank you, that works! One more question, I want to display a image along with the song title. Right now that returns an array of songs ([song1, song2, ...]. How would I go about creating an array of arrays such as [[song1, song1_image], [song2, song_image], ...]

dajwill commented 9 years ago

Nevermind. I have created the array I want, I just can't populate it with the info I want.

Currently the line:

@test = tracks.first.album.images.first

returns

{"height"=>640, "url"=>"https://i.scdn.co/image/3012f6af84d128b2261b54b40dae836d0102a553", "width"=>640}

But when I try to access the url with @test = tracks.first.album.images.first.url I get an error

chrisvfritz commented 9 years ago

Great troubleshooting! So that return is actually a hash. In Ruby, we can't access hashes with a dot, but use square brackets, with the key inside. In this case, they key is "url", so we'd do first["url"]. We know that this is a hash btw because it's in curly braces, with the => (that's called the hash rocket) between keys and values.