I created a child class of Hash and would like to internalize the
equivalent of Hash.new {|hash,key| } The following code failed:
class X < Hash
def initialize
super { |hash,key| ... }
end
end
Any suggestions? I suppose I could do it externally with a create()
wrapper but it doesn't seem very pragmatic.
def create_X
y = X.new {|hash,key| ... }
return y
end
My overall goal is to record a list of attempts to read undefined Keys.
Thanks,
Larry
···
--
Posted via http://www.ruby-forum.com/.
Hi --
I created a child class of Hash and would like to internalize the
equivalent of Hash.new {|hash,key| } The following code failed:
class X < Hash
def initialize
super { |hash,key| ... }
end
end
Any suggestions? I suppose I could do it externally with a create()
wrapper but it doesn't seem very pragmatic.
def create_X
y = X.new {|hash,key| ... }
return y
end
My overall goal is to record a list of attempts to read undefined Keys.
Here's what I did -- I'm not sure how it differs from yours but
hopefully it will help:
class X < Hash
attr_accessor :attempts
def initialize
self.attempts =
super {|h,k| attempts << k unless h.has_key?(k); nil }
end
end
h = X.new
h[1] = 2
p h[1] # 2
p h[0] # nil
p h[2] # nil
p h.attempts # [0,2]
David
···
On Sun, 26 Aug 2007, Larry Fast wrote:
--
* Books:
RAILS ROUTING (new! http://www.awprofessional.com/title/0321509242\)
RUBY FOR RAILS (http://www.manning.com/black\)
* Ruby/Rails training
& consulting: Ruby Power and Light, LLC (http://www.rubypal.com)
Thank you both. Yes, that works. So I'm puzzled by the error I was
getting. Oh well, carrying on...
I still have a related problem. I'm using YML to export and import my
Hash. YML loses all the Hash initialization settings. So I may still
have to create a new internal Hash after reloading from YML.
class X < Hash
attr_accessor :attempts
def initialize
self.attempts = []
super {|h,k| attempts << k unless h.has_key?(k); nil }
end
end
h = X.new
h[1] = 2
p h[1] # 2
p h[0] # nil
p h[2] # nil
p h.attempts # [0,2]
yml_text = YAML.dump(h) # "--- !map:X \n1: 2\n"
j = YAML.load(yml_text) # {1=>2}
j.class # X
j.attempts # nil
j[2] = 25 # 25
j # {1=>2, 2=>25}
j[3] # nil
j.attempts # nil
···
--
Posted via http://www.ruby-forum.com/.