From: "Einar Magnús Boson" Date: 2008-11-20T01:06:38+09:00 Subject: Re: build hash by iterating On 19.11.2008, at 15:31 , Jason Lillywhite wrote: > I am building a hash this way: > > h = {} > i = 0 > j = 24 > > while i < 15 do > h[i] = j > i += 1 > j += 6 > end > > => {5=>54, 11=>90, 0=>24, 6=>60, 12=>96, 1=>30, 7=>66, 13=>102, 2=>36, > 8=>72, 14=>108, 3=>42, 9=>78, 4=>48, 10=>84} > > Just what I need, but doesn't seem very Ruby-friendly > > And if I want to change each hash value from fixnum to string, how > would > that be done? > > this is not working: new_hash = h.each_key {|k| h[k].to_s} > > thank you! > -- > Posted via http://www.ruby-forum.com/. > h = (0...15).inject({}) {|h, i| h[i] = (24+i*6).to_s; h} p h # but this hash makes no sense. # just do h = Array.new(15) {|i| (24+i*6).to_s} p h #then you can index the array: p h[11] p h[5] # >> {5=>"54", 11=>"90", 0=>"24", 6=>"60", 12=>"96", 1=>"30", 7=>"66", 13=>"102", 2=>"36", 8=>"72", 14=>"108", 3=>"42", 9=>"78", 4=>"48", 10=>"84"} # >> ["24", "30", "36", "42", "48", "54", "60", "66", "72", "78", "84", "90", "96", "102", "108"] # >> "90" # >> "54" einarmagnus