Ruby在哈希数组中查找某些东西

时间:2021-11-03 16:00:53

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.

返回一个像链接一样的可链接范围对象。

#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.

返回一个像链接一样的可链接范围对象。