Hash - nested traversal - Ruby - (Any one know this)
I have this hash
hasha = {"a" => "b","a_a" => {"x_y" => "sreeraj","a_b" => "hereIam"}}
I need to change this to
hasha = {"a" => "开发者_StackOverflow中文版b","a-a" => {"x-y" => "sreeraj","a-b" => "hereIam"}}
i.e. I need to change all keys containing "_"
(underscore) to "-"
(minus). How can I do this?
This is might not be the smarter one, but it works:
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
where:
hasha = {"a" => "b","a_a" => {"x_y" => "sreeraj","a_b" => "hereIam"}}
newhash = rep_key hasha
puts newhash.inspect
gives:
newhash = {"a" => "b","a-a" => {"x-y" => "sreeraj","a-b" => "hereIam"}}
Try recursion.
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, "_", "-")
精彩评论