[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

overwriting hash key

jim

9/19/2008 10:40:00 PM

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.
2 Answers

Rob Biedenharn

9/19/2008 10:46:00 PM

0

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

> 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.

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 Biedenharn http://agileconsult...
Rob@AgileConsultingLLC.com



Siep Korteling

9/19/2008 11:19:00 PM

0

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
--
Posted via http://www.ruby-....