tags:

views:

81

answers:

1

Program I'm making has a simple configuration file looking something like this.

@overlays = {
  :foo => "http://www.bar.com",
  :bar => nil,
}

What I need to do is go through this hash and get the following output.

OverlayKey[0]='foo'
OverlayVal[0]='http://www.bar.com'
OverlayKey[1]='bar'
OverlayVal[1]='nil'

In order to keep my configuration like I want it I need some fake index numbers. Would rather not add numbers into the hash, it would make the configuration look a bit ugly. So I been playing around with artificially generating the numbers during output.

This is ugly but I"m just playing around with it currently.

def makenumbers
  @numbers = [] 
  length = @overlays.length - 1
  (0..length).each do |num|
    @numbers.push("#{num}")
  end
end

makenumbers

@overlays.each do |key,val|
  @numbers.each do |num|
    puts "OverlayKey['#{num}']='#{key}'"
    puts "OverlayVal['#{num}']='#{val}'"
  end
end

Which is giving me something like this.

OverlayKey['0']='foo'
OverlayVal['0']='http://www.bar.com'
OverlayKey['1']='foo'
OverlayVal['1']='http://www.bar.com'
OverlayKey['0']='bar'
OverlayVal['0']=''
OverlayKey['1']='bar'
OverlayVal['1']=''

Understand why this doesn't give me the output I want, although after playing with it for a bit I'm not really sure how to do what I want without adding numbers into the hash during configuration. Sure this is pretty simple I just can't seem to wrap my head around it.

+4  A: 

I don't know what the problem is other than Hashes are unsorted by default:

overlays = {
  :foo => "http://www.bar.com",
  :bar => nil,
}

overlays.each_with_index do |(k,v), i|
  puts "OverlayKey['#{i}']=#{k.to_s.inspect}"
  puts "OverlayVal['#{i}']=#{v.to_s.inspect}"
end

Output looks like this:

OverlayKey['0']="bar"
OverlayVal['0']=""
OverlayKey['1']="foo"
OverlayVal['1']="http://www.bar.com"

As a note:

# Instead of this:
"#{num}"
# Use this:
num.to_s
tadman
Other than me being the idiot that read the hash API 3 times today and some how missed with_index. All though I guess thats an enumerable. Thanks.
gregf
Yeah, it's in Enumerable so it's easy to overlook. There's lots of very useful methods in Enumerable that apply to Array and Hash so it's worth reading up on as it can save tons of time with the right call vs. some big hack.
tadman
Upvote for Enumerable - read the API till you know all the different constructions it has, that (small) time spent will pay off generously in long run.
Toms Mikoss