Hackerrank Ruby Hash - Addition, Deletion, Selection Solution

Hackerrank Ruby Hash - Addition, Deletion, Selection Solution

.MathJax_SVG_Display {text-align: center; margin: 1em 0em; position: relative; display: block!important; text-indent: 0; max-width: none; max-height: none; min-width: 0; min-height: 0; width: 100%} .MathJax_SVG .MJX-monospace {font-family: monospace} .MathJax_SVG .MJX-sans-serif {font-family: sans-serif} .MathJax_SVG {display: inline; font-style: normal; font-weight: normal; line-height: normal; font-size: 100%; font-size-adjust: none; text-indent: 0; text-align: left; text-transform: none; letter-spacing: normal; word-spacing: normal; word-wrap: normal; white-space: nowrap; float: none; direction: ltr; max-width: none; max-height: none; min-width: 0; min-height: 0; border: 0; padding: 0; margin: 0} .MathJax_SVG * {transition: none; -webkit-transition: none; -moz-transition: none; -ms-transition: none; -o-transition: none} .mjx-svg-href {fill: blue; stroke: blue}

In this challenge, we will show you ways in which we can add key-value pairs to Hash objects, delete keys from them, and retain them based on a logic.

Consider the following Hash object:

h = Hash.new
h.default = 0

A new key-value pair can be added using or the store method

h[key] = value

or

h.store(key, value)

An existing key can be deleted using the delete method

h.delete(key)

For destructive selection and deletion, we can use keep_if and delete_if as seen in Array-Selection

> h = {1 => 1, 2 => 4, 3 => 9, 4 => 16, 5 => 25}
 => {1 => 1, 2 => 4, 3 => 9, 4 => 16, 5 => 25}
> h.keep_if {|key, value| key % 2 == 0} # or h.delete_if {|key, value| key % 2 != 0}
 => {2 => 4, 4 => 16}

Note

For non-destructive selection or rejection, we can use select, reject, and drop_while similar to Array-Selection

In this challenge, a hash object called hackerrank is already created. You have to add

  • A key-value pair [543121, 100] to the hackerrank object using store
  • Retain all key-value pairs where keys are Integers ( clue : is_a? Integer )
  • Delete all key-value pairs where keys are even-valued.

Solution in ruby

Approach 1.

hackerrank.store(543121,100)
hackerrank.keep_if {|a| a.is_a? Integer}
hackerrank.delete_if {|a| a.even?}

Approach 2.

hackerrank[543121] = 100

hackerrank.keep_if  {|key, value| key.is_a? Integer}

hackerrank.delete_if {|key, value| key%2==0}

Approach 3.

# Enter your code here. 
hackerrank[543121]=100
hackerrank.keep_if {|k,v| k.is_a? Integer }
hackerrank.delete_if {|k,v| k%2 == 0}

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe