无法在哈希中访问密钥的值

时间:2017-05-12 02:45:49

标签: ruby-on-rails ruby rubygems

我正在使用Rspotify gem(它是Spotify API的包装器),我试图访问下面数组中第一张图片的网址:

[# < 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
  }]
]

我可以使用artist.images.first进行以下操作,但我无法通过链接来访问其中的网址(例如.url["url"]("url")[:url]):

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

这是我的控制人员:

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

以下是我的观点:

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

1 个答案:

答案 0 :(得分:2)

使用artist.images.first ['url']应该解决它。

以下代码对我有用:

require 'rspotify'

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

puts artist.images.first['url']