简体   繁体   中英

How to delete an array inside a hash

I have a hash that looks like this:

my_hash = {"positions"=>[[2, 3, 13, 56], [2, 3, 13]]}

I would like to delete the first array inside of the hash:

wanted_hash == {"positions"=> [2, 3, 13]}

I tried:

wanted_hash = my_hash.values[0].pop

but this removes the wrong array. I'm not sure why, but it removes [2,3,13] .

pop is removing the last element of an array. Try shift instead.

You can use transform_values and select the second element from the array in positions :

my_hash = {"positions"=>[[2, 3, 13, 56], [2, 3, 13]]}
wanted_hash = my_hash.transform_values { |value| value[1] }
# {"positions"=>[2, 3, 13]}

Notice it doesn't modify my_hash , it returns a new object.

Carried out this series of steps in irb. This is assuming that you want to mutate my_hash:

my_hash = {"positions"=>[[2, 3, 13, 56], [2, 3, 13]]}
# => {"positions"=>[[2, 3, 13, 56], [2, 3, 13]]} 
my_hash["positions"].shift
# => [2, 3, 13, 56] 
my_hash
# => {"positions"=>[[2, 3, 13]]} 
my_hash["positions"].flatten!
# => [2, 3, 13] 
my_hash
# => {"positions"=>[2, 3, 13]} 

So, it comes down to:

my_hash["positions"].shift
my_hash["positions"].flatten!

This can be done with non-destructive each_with)object method:

my_hash.each_with_object({}) { |(k, v), h| h[k] = v[1]} my_hash.each_with_object({}) { |(k, v), h| h[k] = v[1]} .

If you use ruby version < 2.4.0 (where transform_values method was introduced) this could help.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM