# Overwriting hash key

**URL:** <https://www.ruby-forum.com/t/overwriting-hash-key/149074>\
**Category:** Ruby\
**Created:** [September 20, 2008, 12:45am UTC](https://www.ruby-forum.com/t/overwriting-hash-key/149074 "2008-09-20T00:45:23Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![jim](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/ac91a4/32.png) [@jim](https://www.ruby-forum.com/u/jim)\
**Post date:** [September 20, 2008, 12:45am UTC](https://www.ruby-forum.com/t/overwriting-hash-key/149074/1 "2008-09-20T00:45:23Z")

</div>

How can get Ruby to tell me when I’m overwriting an existing key in my  
hash?

For example,

h = { “key1” =\> [6, 44, 12],  
“key2” =\> [8, 1],  
.  
.  
}

The hash could get big enough where I accidentally add a new entry,

```
     "key1" => [99, 3]

```

when what I needed to do was add [99, 3] to key1’s array. I won’t get  
any warning that the first occurrence of key1 is being replaced.

---

<div class="post-metadata">

**Author:** ![jim](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/ac91a4/32.png) [@jim](https://www.ruby-forum.com/u/jim)\
**Post date:** [September 20, 2008, 12:54am UTC](https://www.ruby-forum.com/t/overwriting-hash-key/149074/2 "2008-09-20T00:54:46Z")

</div>

On Sep 19, 2008, at 6:37 PM, jim wrote:

> The hash could get big enough where I accidentally add a new entry,
> 
> ```
> "key1" => [99, 3]
> 
> ```
> 
> when what I needed to do was add [99, 3] to key1’s array. I won’t get  
> any warning that the first occurrence of key1 is being replaced.

Well, if you always have arrays for the values, you can start with:

h = Hash.new {|h,k| h[k] = []}

Then initialize your hash with:

h.update({ “key1” =\> [6, 44, 12],  
“key2” =\> [8, 1],  
…  
})

Then you can:  
h[“key1”] \<\< 99 \<\< 3  
h[“key1”].concat([99, 3])  
h[“key1”].push(99, 3)

h[“key1”] has [6,44,12,99,3]

-Rob

Rob B. [http://agileconsultingllc.com](http://agileconsultingllc.com)  
removed\_email\_address@domain.invalid

---

<div class="post-metadata">

**Author:** ![jim](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/ac91a4/32.png) [@jim](https://www.ruby-forum.com/u/jim)\
**Post date:** [September 20, 2008, 1:26am UTC](https://www.ruby-forum.com/t/overwriting-hash-key/149074/3 "2008-09-20T01:26:41Z")

</div>

jim wrote:  
(…)

> The hash could get big enough where I accidentally add a new entry,
> 
> ```
> "key1" => [99, 3]
> 
> ```
> 
> when what I needed to do was add [99, 3] to key1’s array. I won’t get  
> any warning that the first occurrence of key1 is being replaced.

Here you go:

class SafeHash \<Hash  
def []=(k,v)  
if self.keys.include?(k) then  
print “Are you really, sure you want to overwrite #{k.to\_s}? (Y/N)”  
STDOUT.flush  
super(k,v) if gets.chomp.downcase == “y”  
else  
super(k,v)  
end  
end  
end

h = SafeHash.new  
h[“key1”] = [99,3]  
h[“key1”] = [12,4]  
p h

Regards,

Siep
