Ruby在哈希數組中查找某些東西

[英]Ruby Finding Something in an Array of Hashes


I am trying to learn Ruby and I have the following code

我正在嘗試學習Ruby,我有以下代碼

 a[0]={ :artist => 'Green Day',
                          :name => 'Song1',
                                                   :bitrate => 192 }
 a[1]={ :artist => 'U2', :name => 'Song2' }
 a[2]={:artist => 'Metallica', :name => 'Battery' }

My question is how do I find in such an array all the songs by Metallica, for example? Thank you! :)

我的問題是如何在這樣的數組中找到Metallica的所有歌曲?謝謝! :)

Edit: Ok, another newbie question? How can I find the songs that contain a certain sequence in their titles?

編輯:好的,另一個新手問題?如何在標題中找到包含特定序列的歌曲?

I tried:

我試過了:

a.find { |x| x[:song].include? 'Song' }

but it returns an error.

但它返回一個錯誤。

3 个解决方案

#1


2  

a.select { |song| song[:artist] == 'Metallica' }

and for your second question

而對於你的第二個問題

a.select { |song| song[:name].include? 'Song' }

#2


8  

You can use select method

您可以使用select方法

a.select {|c| c[:artist] == 'U2'}

#3


-1  

Employee.where("artist = ?", "Metallica")

returns a chainable scope object that acts like an array.

返回一個像鏈接一樣的可鏈接范圍對象。


注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2012/10/30/72506478022b2d6f93ad1634af68ad7e.html



 
粤ICP备14056181号  © 2014-2020 ITdaan.com