Home > OS >  Adding multiple values to a key in Ruby as well as delete just one value associated
Adding multiple values to a key in Ruby as well as delete just one value associated

Time:12-05

I want to add values and delete values to the hash like below

h= {:a =>[ 1,3, 4],
    :b =>[ 3, 6],
    :c =>[ 4, 8, 87]
   }

and how do I delete just one value pertaining to a key? remove c, 87

h= {:a =>[ 1,3, 4],
    :b =>[ 3, 6],
    :c =>[ 4, 8]
   }

Can I do this in ruby? I am new to ruby, Can someone help me out?

CodePudding user response:

Use a Nil Guard

You need to guard against missing keys and values in your Hash. There are a number of ways to do this, but on any recent Ruby the &. operator ensures that a method doesn't raise an exception if called on nil. The following works fine:

h = {
  a: [1, 3, 4],
  b: [3, 6],
  c: [4, 8, 87]
}

h[:c]&.delete 87; h
#=> {:a=>[1, 3, 4], :b=>[3, 6], :c=>[4, 8]}

h[:x]&.delete 101; h
#=> {:a=>[1, 3, 4], :b=>[3, 6], :c=>[4, 8]}
  • Related