Question

I have an array of hashes, like this:

my_array = [{foo:1,bar:"hello",baz:3},{foo:2,bar:"hello2",baz:495,foo_baz:"some_string"},...] 
#there can be arbitrary many in this list.
#There can also be arbitrary many keys on the hashes.

I want to create a new array that is a copy of the last array, except that I remove any :bar entries.

my_array2 = [{foo:1,baz:3},{foo:2,baz:495,foo_baz:"some_string"},...]

I can get the my_array2 by doing this:

my_array2 = my_array.map{|h| h.delete(:bar)}

However, this changes the original my_array, which I want to stay the same.

Is there a way of doing this without having to duplicate my_array first?

Was it helpful?

Solution

one of many ways to accomplish this:

my_array2 = my_array.map{|h| h.reject{|k,v| k == :bar}}

OTHER TIPS

my_array.map {|h| h.select{|k, _| k != :bar} }
# => [{:foo=>1, :baz=>3}, {:foo=>2, :baz=>495, :foo_baz=>"some_string"}]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top