3

I have an array of hashes.

rabbits = [{:color=>"blue", :height=>5, :name=>"Charles"}, {:color=>"red", :height=>12, :name=>"Henry"}, {:color=>"green", :height=>7, :name=>"Francis"}, {:color=>"purple", :height=>3, :name=>"William"}]

How would one create an array from this array of just the :height?

I tried: rabbits.map(&:height) and rabbits.map{|i| i.height} but neither worked.

Goal is to have height_array = [5, 12, 7, 3]

3 Answers 3

6

This will work

rabbits.map{|c| c[:height] }

The other two methods that you tried expect height to be a method on c which is not the case.

Sign up to request clarification or add additional context in comments.

4 Comments

Thank you so much! I tried that but was not storing it as a new array. So when I tried to print cats on the next line it was giving me the original. Thanks again.
To rewrite the original array use cat.map! ... (note the exclamations mark). But I'd save it to another variable, ages = cats.map ...
Thanks Sergio. I did not know about that. Answer accepted. :)
I was asked to edit the question because it was part of a coding challenge and the curator was worried future students would be able to find this and use it for their answer. cats.map should equal rabbits.map and cats_age should equal height . Sorry for this inconvenience. :(
0
arr = cats.collect{|c| c[:cats_age] }

2 Comments

That's an alias for map, isn't it? :)
@Salil I was asked to edit the question because it was part of a coding challenge and the curator was worried future students would be able to find this and use it for their answer. cats.collect should equal rabbits.collect and cats_age should equal height . Sorry for this inconvenience. :(
0
rabbits.inject([]) {|height,hash| height << hash[:height]}

3 Comments

Seems to me that using inject is an overkill here :)
indeed it is but just listed down as an option
@AshishSaihgal I was asked to edit the question because it was part of a coding challenge and the curator was worried future students would be able to find this and use it for their answer. cats.inject should equal rabbits.inject and cats_age should equal height . Sorry for this inconvenience. :(

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.