问题描述
我有一个条件,我得到一个散列
hash = {_id=>4de7140772f8be03da000018, .....}
我想把这个散列作为
hash = {id=>4de7140772f8be03da000018,......}
$ b PS :我不知道哈希中的密钥是什么,它们是随机的,每个密钥都带有一个_前缀如果所有的键都是字符串,并且它们都带有下划线前缀,那么你可以修补它们,而不需要下划线。 这个散列:
h.keys.each {| k | h [k [1,k.length-1]] = h [k]; h.delete(k)}
位抓取除第一个字符以外的所有 k
。如果你想要一个副本,那么:
new_h = Hash [h.map {| k,v | [k [1,k.length - 1],v]}]
或
new_h = h.inject({}){| x,(k,v)| x [k [1,k.length-1]] = v; x}
您也可以使用如果你不喜欢<$ c用于提取子字符串的符号:
h.keys.each {| $ c $ k>]
K | h [k(n)] = h [k]; h.delete(k)}
Hash [h.map {| k,v | [k.sub(/ \ A_ /,''),v]}]
h.inject({}){| x,(k,v)| x [k.sub(/ \A_ /,'')] = v; x}
如果只有一些键具有下划线前缀:
h.keys.each do | k | (k [0,1] =='_')
h [k [1,k.length - 1]] = h [k]
h.delete(k)$
b $ b end
end
可以对上面的所有其他变体进行类似的修改,但是这两个:
Hash [h.map {| k,v | [k.sub(/ \ A_ /,''),v]}]
h.inject({}){| x,(k,v)| x [k.sub(/ \A_ /,'')] = v; x}
应该没有下划线前缀且没有额外修改的键。
I have a condition where, I get a hash
hash = {"_id"=>"4de7140772f8be03da000018", .....}
and I want this hash as
hash = {"id"=>"4de7140772f8be03da000018", ......}
P.S: I don't know what are the keys in the hash, they are random which comes with an "_" prefix for every key and I want no underscores
If all the keys are strings and all of them have the underscore prefix, then you can patch up the hash in place with this:
h.keys.each { |k| h[k[1, k.length - 1]] = h[k]; h.delete(k) }
The k[1, k.length - 1]
bit grabs all of k
except the first character. If you want a copy, then:
new_h = Hash[h.map { |k, v| [k[1, k.length - 1], v] }]
Or
new_h = h.inject({ }) { |x, (k,v)| x[k[1, k.length - 1]] = v; x }
You could also use sub
if you don't like the k[]
notation for extracting a substring:
h.keys.each { |k| h[k.sub(/\A_/, '')] = h[k]; h.delete(k) }
Hash[h.map { |k, v| [k.sub(/\A_/, ''), v] }]
h.inject({ }) { |x, (k,v)| x[k.sub(/\A_/, '')] = v; x }
And, if only some of the keys have the underscore prefix:
h.keys.each do |k|
if(k[0,1] == '_')
h[k[1, k.length - 1]] = h[k]
h.delete(k)
end
end
Similar modifications can be done to all the other variants above but these two:
Hash[h.map { |k, v| [k.sub(/\A_/, ''), v] }]
h.inject({ }) { |x, (k,v)| x[k.sub(/\A_/, '')] = v; x }
should be okay with keys that don't have underscore prefixes without extra modifications.
这篇关于如何用另一个键替换散列键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!