Search code examples
ruby-on-railsrubyruby-on-rails-3ruby-on-rails-3.1

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?


Solution

  • If you just want to extract all the names, use collect (or its map alias) to call the name method on each element of the array and collect the results in another array:

    names = a.collect(&:name)