From: Austin Ziegler Date: 2008-05-15T00:04:17+09:00 Subject: Re: changing hash key On Wed, May 14, 2008 at 10:53 AM, Tim Wolak wrote: > I've been looking for a way to change a hash key. In my code I'm trying > to change the key from a number to a string. Do I need to convert the > key to a string and put it new value in there or is my code wrong? > def numbers > @skty = Hash.new(0) > @sktynl.each do |key, value| > if key <= "39" > key = "SKTY" > @skty[key] += value # !> instance variable @skty > not initialized > elsif key >="40" > key = "SKYNY" > @skty[key] += value > end First, your comparison isn't against numbers, but against strings: irb(main):001:0> "5" <= "40" => false If your keys are truly numbers, use numeric comparisons. Second, I suspect the problem isn't that @skty (which is a *really* bad variable name, by the way) isn't initialized, but that @skty[key] isn't initialized. Which is true because you're not initializing the value, you're just providing a default value if the key isn't found. If you need to initialize an unfound value, you need the block form of Hash.new: @skty = Hash.new { |h, k| h[k] = 0 } -austin -- Austin Ziegler * halostatue@gmail.com * http://www.halostatue.ca/ * austin@halostatue.ca * http://www.halostatue.ca/feed/ * austin@zieglers.ca