priscylam
priscylam

Reputation: 1

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.

Upvotes: 0

Views: 70

Answers (2)

BTL
BTL

Reputation: 4656

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] } }

Upvotes: 1

Yakov
Yakov

Reputation: 3191

I'd use map and slice methods:

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

Upvotes: 3

Related Questions