'Create new array with key from an existing array - Ruby

I have this hash:

my_hash = [
  {
    :name=> 'fiat 500',
    :things=> %w[gps bluetooth automatico],
    :year=> '2021'
  },
  {
    :name=> 'fusca',
    :things=> %w[som dvd automatico],
    :year=> '2022'
  }

]

I want to create a new array but only with the key :year, where would be like this:

 new_array = [
 {
    :year=> '2021'
  },
  {
    :year=> '2022'
  }
]

I'm a beginner in ruby ​​and I can't do it.



Solution 1:[1]

I'd use map and slice methods:

new_array = my_array.map { |item| item.slice(:year) }

Solution 2:[2]

You can use the method map for that.

Ruby doc: https://ruby-doc.org/core-3.0.0/Array.html#method-i-map

new_array = my_hash.map { |h| { :year => h[:year] } }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Yakov
Solution 2 Yakov