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.
CodePudding user response:
I'd use map and slice methods:
new_array = my_array.map { |item| item.slice(:year) }
CodePudding user response:
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] } }
