简体   繁体   中英

Remove specific key set which is an array from a hash

I am trying to remove the elements in an array from a hash and the array forms part of the 'keys' in a hash. Here is an illustration.

hash = {'a' = 1, 'b' = 2, 'c' =3, 'd' = 4}

arr = ["a","d"] #Now I need to remove the elements from this array from the above hash

Resultant hash should be as below

new_hash = {'b' = 2,'c' =3}

This is what I tried unfortunately it doesn't seem to work

for i in 0..hash.length-1

  arr.each do |key_to_del|

    hash.delete key_to_del unless h.nil?

  end

 end

Your hash isn't correct format. It should be like this.

hash={"a"=>1, "b"=>2, "c"=>3, "d"=>4}
arr=["a","d"]

Solution 1

hash.reject! {|k, v| arr.include? k }

Solution 2

arr.each{|v| hash.delete(v)}

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