0

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.

1
  • 3
    "I have this hash: my_hash = [...]" – that's actually an array. Commented Jan 21, 2022 at 9:15

2 Answers 2

3

I'd use map and slice methods:

new_array = my_array.map { |item| item.slice(:year) }
Sign up to request clarification or add additional context in comments.

4 Comments

just for note, between the 2 answers. in the case that there is no "year" in a record of the array, this one returns an empty hash, and the other answer returns a hash with the :year set to nil
That's true. As it's not stated in the question I assume that the key is always present.
Instead of my_array, it should be my_hash - @Yakov
@BhushanKalode it's my_hash in the question, but actually, it's an array of hashes
1

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

1 Comment

sorry, I accidentally edited your answer instead of mine. I've reverted it back.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.