散列 - 嵌套遍历 - Ruby - (任何人都知道这个)

Sre*_*raj 0 ruby hash ruby-on-rails

我有这个哈希

hasha = {"a" => "b","a_a" => {"x_y" => "sreeraj","a_b" => "hereIam"}}
Run Code Online (Sandbox Code Playgroud)

我需要改变它

hasha = {"a" => "b","a-a" => {"x-y" => "sreeraj","a-b" => "hereIam"}}
Run Code Online (Sandbox Code Playgroud)

即我需要将包含"_"(下划线)的所有键更改为"-"(减号).我怎样才能做到这一点?

Emi*_*ggi 6

这可能不是更聪明的,但它有效:

def rep_key(hash={})  
    newhash={}
    hash.each_pair do |key,val|
        val = rep_key(val) if val.class == Hash
        newhash[key.sub(/_/,'-')] = val
    end
    newhash
end
Run Code Online (Sandbox Code Playgroud)

哪里:

hasha = {"a" => "b","a_a" => {"x_y" => "sreeraj","a_b" => "hereIam"}}
newhash = rep_key hasha
puts newhash.inspect
Run Code Online (Sandbox Code Playgroud)

得到:

newhash = {"a" => "b","a-a" => {"x-y" => "sreeraj","a-b" => "hereIam"}}
Run Code Online (Sandbox Code Playgroud)