简体   繁体   中英

Can't access value of key in hash

I'm using the Rspotify gem (it's a wrapper for the Spotify API), and I'm trying to access the url of the first image in the below array:

[# < RSpotify::Artist: 0x007f8558147050 @images = [{
    "height" => 640, "url" => "https://i.scdn.co/image/cb080366dc8af1fe4dc90c4b9959794794884c66", "width" => 640
  }, {
    "height" => 320, "url" => "https://i.scdn.co/image/6bd672a0f33705eda4b543c304c21a152f393291", "width" => 320
  }, {
    "height" => 160, "url" => "https://i.scdn.co/image/085ae2e76f402468fe9982851b51cf876e4f20fe", "width" => 160
  }]
]

I'm able to get to the following using artist.images.first , but I can't access the URL in it by chaining anything (eg .url , ["url"] , ("url") , [:url] ):

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

Here's my controller:

def search
  unless params[:artist][:artist_name].blank?
    artist = params[:artist][:artist_name]
    @artists = RSpotify::Artist.search(artist)
    render 'pages/profile'
  end
end

Here's my view:

<h1> Search Results </h1>
<ul>
 <% @artists.each do |artist| %>
   <li> <%= artist.images.first['url'] %> | <%= artist.name %> </li>
 <% end %>
</ul>

Using artist.images.first['url'] should solve it.

The following code worked for me:

require 'rspotify'

artist = RSpotify::Artist.search('Arctic Monkeys').first

puts artist.images.first['url']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM