我有这个哈希
hasha = {"a" => "b","a_a" => {"x_y" => "sreeraj","a_b" => "hereIam"}}
我需要将其更改为
hasha = {"a" => "b","a-a" => {"x-y" => "sreeraj","a-b" => "hereIam"}}
即。我需要将包含"_"
(下划线)的所有密钥更改为"-"
(减号)。我怎么能这样做?
答案 0 :(得分: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
其中:
hasha = {"a" => "b","a_a" => {"x_y" => "sreeraj","a_b" => "hereIam"}}
newhash = rep_key hasha
puts newhash.inspect
给出:
newhash = {"a" => "b","a-a" => {"x-y" => "sreeraj","a-b" => "hereIam"}}
答案 1 :(得分:3)
尝试递归。
def replace_all(x, a, b)
return if x.class != Hash
y = Hash.new
x.each do |k,v|
if(v.class == Hash)
v = replace_all(v, a, b)
end
if k.class == String and k.include?(a)
y[k.gsub(a,b)] = v
else
y[k] = v
end
end
return y
end
hasha = {"a" => "b","a_a" => {"x_y" => "sreeraj","a_b" => "hereIam"}}
puts replace_all(hasha, "_", "-")