Hello coders, In this post, you will learn how to solve HackerRank Ruby Hash Addition, Deletion, Selection Solution. This problem is a part of the Ruby Tutorial series. One more thing to add, don’t straight away look for the solutions, first try to solve the problems by yourself. If you find any difficulty after trying several times, then look for the solutions.

HackerRank Ruby Hash Addition, Deletion, Selection
Let’s get started with Ruby Hash Addition, Deletion, Selection Solution
Problem Statement
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
methodh[key] = value
or
h.store(key, value)
- An existing key can be deleted using the
delete
methodh.delete(key) - For destructive selection and deletion, we can use
keep_if
anddelete_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 usingstore
- Retain all key-value pairs where keys are Integers ( clue : is_a? Integer )
- Delete all key-value pairs where keys are even-valued.
HackerRank Ruby Hash Addition, Deletion, Selection Solution
hackerrank.store(543121,100) hackerrank.keep_if {|a| a.is_a? Integer} hackerrank.delete_if {|a| a.even?}
Note: This problem (Ruby Hash Addition, Deletion, Selection) is generated by HackerRank but the solution is provided by Chase2Learn. This tutorial is only for Educational and Learning purpose.