How to freeze the key/value association in a hash?

Once a key gets a value, can I make the association freeze?

For example:

hash = {}
hash[:abc] = “abc”.freeze

What I want is that hash[:abc] cannot be re-assigned to another value.

hash[:abc] = “def” # I want this impossible, maybe raise an exception.

h = {
‘a’ => 1,
‘b’ => 2,
}

puts h[‘c’]

–output:–
nil

class MyHash < Hash
alias :old :[]=

def[]=(key, val)

if self[key] == nil
  old(key, val)
else
  raise "Operation not allowed!"
end

end

end

my_h = MyHash.new
my_h[‘c’] = 2
puts my_h[‘c’]

–output:–
2

my_h[‘c’] = 3

–output:–
ruby.rb:16:in `[]=’: Operation not allowed! (RuntimeError)
from ruby.rb:25

Good idea! Thank you, 7stud!

7stud – wrote in post #1006557:

def[]=(key, val)

if self[key] == nil
  old(key, val)
else
  raise "Operation not allowed!"
end

Since nil is an allowed value, I’d say it’s better to use has_key?

def []=(key,val)
raise “Operation not allowed!” if has_key?(key)
old(key,val)
end

Note that there are still other methods which may mutate the hash
(update, replace, clear etc)