2017-05-12 37 views
-1

我使用訪問鍵的值Rspotify gem(這對Spotify的API的包裝),而我試圖訪問第一圖像的URL以下數組中:不能在哈希

[# < 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])訪問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> 
+0

你得到這個做? 'artist.images.first.class' –

+0

'<%= artist.images.first.url%>'它似乎不是一個散列,它是'檢查'的實現方式。你會收到什麼錯誤信息btw? – mudasobwa

+0

@ Md.FhanhanMemon它說這是一個哈希。 @mudasobwa我得到以下內容:未定義的方法'url'爲#。 –

回答

2

使用artist.images.first [ '網址']應該解決這個問題。

下面的代碼爲我工作:

require 'rspotify' 

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

puts artist.images.first['url'] 
+0

我收到以下錯誤:未定義的方法'[]'nil:NilClass。我用我的控制器和查看代碼更新了我的帖子。 –

+0

如果藝術家沒有圖像,可能會出現此錯誤。添加一個安全檢查,如「if artist.images.any?」 – Matt

+0

藝術家有圖像。這是我包括在我的文章中的同一位藝術家。 –