Hash as a class variable

Hi ruby fans,

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.

ciao,
   Oliver

Hi ruby fans,

Hello.

I am a python2ruby switcher and just encountered this problem today
with a class variable:

---
class Testclass
  @@myhash = Hash.new({"a"=>"aaaah"})

In this line, you create a Hash and set the default value for new keys to another Hash. I believe you meant simply:

@@myhash = {"a" => "aaaah"}

  def initialize()
    p @@myhash
  end
end
T = Testclass.new
---

Welcome to Ruby!

James Edward Gray II

···

On Oct 12, 2005, at 9:06 AM, OliverMarchand wrote:

OliverMarchand wrote:

Hi ruby fans,

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})

Kind regards

    robert

@@myhash = { "a" => "aaaah" }
or
    @@myhash = Hash[ "a" => "aaaah" ]

this is what you wrote means:

   irb:~/eg/ruby > irb
   irb(main):001:0> h = Hash::new({ 'the default' => 'value' })
   => {}

   irb(main):002:0> h[42]
   => {"the default"=>"value"}

hth.

-a

···

On Wed, 12 Oct 2005, OliverMarchand wrote:

Hi ruby fans,

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

===============================================================================