M
m4dc4p
I am trying to figure out how I can modify the Hash object so that I am
notified each time a key is inserted in a Hash when it is constructed
using the syntax below:
a = { "x" => "1", "y" => "2" }
I've tried overriding []=, but that will only get called when the Hash
is constructed explicitly.
Here's a little bit of code showing what I've tried and the output I'd
like to see. Thanks for any help!
class Hash
alias ld_assignment :[]=
def []=(key, value)
puts "#{key} => #{value}"
old_assignment(key, value)
end
end
puts "Creating a"
a = { "x" => "1", "y" => "2" }
puts "Creating b"
b = Hash.new
b["1"] = "x"
b["2"] = "y"
# Expected output
# Creating a
# x => 1
# y => 2
# Creating b
# 1 => x
# 2 => y
# Actual output
# Creating a
# Creating b
# 1 => x
# 2 => y
p.s. I'm ultimately doing this to get to an OrderedHash. I looked at
Ara's code but the problem is I need to *replace* the functionality of
Hash - it's not an option for me to explicitly create an OrderedHash
object.
p.p.s. Is there a way to avoid the alias statement for []=? For some
reason, calling super in there would give a NoMethodError.
notified each time a key is inserted in a Hash when it is constructed
using the syntax below:
a = { "x" => "1", "y" => "2" }
I've tried overriding []=, but that will only get called when the Hash
is constructed explicitly.
Here's a little bit of code showing what I've tried and the output I'd
like to see. Thanks for any help!
class Hash
alias ld_assignment :[]=
def []=(key, value)
puts "#{key} => #{value}"
old_assignment(key, value)
end
end
puts "Creating a"
a = { "x" => "1", "y" => "2" }
puts "Creating b"
b = Hash.new
b["1"] = "x"
b["2"] = "y"
# Expected output
# Creating a
# x => 1
# y => 2
# Creating b
# 1 => x
# 2 => y
# Actual output
# Creating a
# Creating b
# 1 => x
# 2 => y
p.s. I'm ultimately doing this to get to an OrderedHash. I looked at
Ara's code but the problem is I need to *replace* the functionality of
Hash - it's not an option for me to explicitly create an OrderedHash
object.
p.p.s. Is there a way to avoid the alias statement for []=? For some
reason, calling super in there would give a NoMethodError.