I am a python2ruby switcher and just encountered this problem today
with a class variable:
···
---
class Testclass
@@myhash = Hash.new({"a"=>"aaaah"})
def initialize()
p @@myhash
end
end
T = Testclass.new
---
yields
{}
whixh surprises me, becasue I would expect myhash to have an entry and
not be the empty hash. The only way I found to fix this was:
---
class Testclass
@@myhash = nil
def initialize()
@@myhash = Hash.new()
@@myhash["a"] = "aaaah"
p @@myhash
end
end
T = Testclass.new
---
which yields what I expect:
{"a"=>"aaaah"}
I have searched in the FAQ's, Things to know about ruby, websites, etc.
but just couldn't find any hint. Examples are never hashes.
I am a python2ruby switcher and just encountered this problem today
with a class variable:
---
class Testclass
@@myhash = Hash.new({"a"=>"aaaah"})
def initialize()
p @@myhash
end
end
T = Testclass.new
---
yields
{}
class Testclass
@@myhash = {"a"=>"aaaah"}
def initialize()
p @@myhash
end
end
=> nil
T = Testclass.new
{"a"=>"aaaah"}
=> #<Testclass:0x10188fb0>
You are providing a default value to the hash:
h=Hash.new("foo")
=> {}
h[1]
=> "foo"
h[2]
=> "foo"
h
=> {}
If you need to create a filled hash using {} is enough. There is no such
thing as a copy constructor. If you need to explicitely call Hash.new you
need to use #update:
h=Hash.new("foo").update(1=>2, 3=>4)
=> {1=>2, 3=>4}
h
=> {1=>2, 3=>4}
h[111]
=> "foo"
Note that update(1=>2, 3=>4) is a shortcut for update({1=>2, 3=>4})
I am a python2ruby switcher and just encountered this problem today
with a class variable:
---
class Testclass
@@myhash = Hash.new({"a"=>"aaaah"})
--
email :: ara [dot] t [dot] howard [at] noaa [dot] gov
phone :: 303.497.6469
Your life dwells amoung the causes of death
Like a lamp standing in a strong breeze. --Nagarjuna