overwriting hash key

J

jim

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],
 
R

Rob Biedenharn

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://agileconsultingllc.com
(e-mail address removed)
 
S

Siep Korteling

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,537
Members
45,020
Latest member
GenesisGai

Latest Threads

Top