Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Join Ruby hash keys into string

I'm trying to create a Ruby template on the fly with Chef attributes but I can't figure out how to map the attributes to output the way I need.

Example Hash:

a = { 
    "route" => { 
        "allocation" => {
            "recovery" => {
                "speed" => 5,
                "timeout" => "30s"
            },
            "converge" => {
                "timeout" => "1m"
            }
        }
    }
}

Would turn into:

route.allocation.recovery.speed: 5
route.allocation.recovery.timeout: 30s
route.allocation.converge.timeout: 1m

Thanks for the help.

like image 485
jarsever Avatar asked Dec 01 '25 06:12

jarsever


1 Answers

You can use recursion if your hash is not large enough to throw stack overflow exception. I don't know what are you trying to achieve, but this is example of how you can do it:

a = { 
    "route" => { 
        "allocation" => {
            "recovery" => {
                "speed" => 5,
                "timeout" => "30s"
            },
            "converge" => {
                "timeout" => "1m"
            }
        }
    }
}

def show hash, current_path = ''
  hash.each do |k,v|
    if v.respond_to?(:each)
      current_path += "#{k}."
      show v, current_path
    else
      puts "#{current_path}#{k} : #{v}"
    end
  end
end

show a

Output:

route.allocation.recovery.speed : 5 
route.allocation.recovery.timeout : 30s
route.allocation.recovery.converge.timeout : 1m 
like image 91
Roman Pushkin Avatar answered Dec 03 '25 20:12

Roman Pushkin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!