简体   繁体   中英

Trying to filter a key in a nested hash inside an array

i have the following array:

[#<PatchedOpenStruct name="Kristen Stewart", id="162655167", characters=["Snow White"]>, #<PatchedOpenStruct name="Chris Hemsworth", id="770829335", ch
aracters=["The Huntsman"]>, #<PatchedOpenStruct name="Charlize Theron", id="162654733", characters=["The Queen"]>, #<PatchedOpenStruct name="Viggo Mort
ensen", id="162654541">, #<PatchedOpenStruct name="Sam Claflin", id="771073196", characters=["Prince"]>]

i am trying to filter all the 'name' fields from this. any help?

如果只想提取所有名称,请使用collect (或其map别名)在数组的每个元素上调用name方法,并将结果收集在另一个数组中:

names = a.collect(&:name)

Two ways I can think of to do this if these were standard OpenStructs.

array_of_things.collect{|each_thing| each_thing.name} array_of_things.collect{|each_thing| each_thing.name} returns an array of all the names of all the things. array_of_things.select{|each_thing| each_thing.name =~ /Kristen/} array_of_things.select{|each_thing| each_thing.name =~ /Kristen/} returns an array of things with names that match the expression /Kristen/ .

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