我有一个条件,我得到一个哈希
hash = {"_id"=>"4de7140772f8be03da000018", .....}
我希望这个哈希为
hash = {"id"=>"4de7140772f8be03da000018", ......}
P.S:我不知道哈希中的键是什么,它们是随机的,每个键都有一个“_”前缀,我不想要下划线
如果所有键都是字符串并且所有键都有下划线前缀,那么您可以使用以下方法修补哈希值:
h.keys.each { |k| h[k[1, k.length - 1]] = h[k]; h.delete(k) }
除了第一个角色之外,k[1, k.length - 1]
位抓住了所有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 }
如果你不喜欢用于提取子字符串的sub
表示法,你也可以使用k[]
:
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 }
并且,如果只有一些键具有下划线前缀:
h.keys.each do |k|
if(k[0,1] == '_')
h[k[1, k.length - 1]] = h[k]
h.delete(k)
end
end
可以对上面的所有其他变体进行类似的修改,但这两个变体:
Hash[h.map { |k, v| [k.sub(/\A_/, ''), v] }]
h.inject({ }) { |x, (k,v)| x[k.sub(/\A_/, '')] = v; x }
没有额外修改的键没有下划线前缀应该没问题。
hash[:new_key] = hash.delete :old_key
rails Hash有标准方法:
hash.transform_keys{ |key| key.to_s.upcase }
http://api.rubyonrails.org/classes/Hash.html#method-i-transform_keys
UPD:ruby 2.5方法
你可以做
hash.inject({}){|option, (k,v) | option["id"] = v if k == "_id"; option}
这适用于您的情况!
h.inject({}) { |m, (k,v)| m[k.sub(/^_/,'')] = v; m }
如果我们想要重命名哈希中的特定键,那么我们可以按如下方式执行:
假设我的哈希是 my_hash = {'test' => 'ruby hash demo'}
现在我想用'message'替换'test',然后:
my_hash['message'] = my_hash.delete('test')
hash.each {|k,v| hash.delete(k) && hash[k[1..-1]]=v if k[0,1] == '_'}
我做得过头了,想出了以下内容。我背后的动机是在合并/展平哈希时附加哈希键以避免范围冲突。
向Hash实例添加重定密钥方法。
# Adds additional methods to Hash
class ::Hash
# Changes the keys on a hash
# Takes a block that passes the current key
# Whatever the block returns becomes the new key
# If a hash is returned for the key it will merge the current hash
# with the returned hash from the block. This allows for nested rekeying.
def rekey
self.each_with_object({}) do |(key, value), previous|
new_key = yield(key, value)
if new_key.is_a?(Hash)
previous.merge!(new_key)
else
previous[new_key] = value
end
end
end
end
my_feelings_about_icecreams = {
vanilla: 'Delicious',
chocolate: 'Too Chocolatey',
strawberry: 'It Is Alright...'
}
my_feelings_about_icecreams.rekey { |key| "#{key}_icecream".to_sym }
# => {:vanilla_icecream=>"Delicious", :chocolate_icecream=>"Too Chocolatey", :strawberry_icecream=>"It Is Alright..."}
{ _id: 1, ___something_: 'what?!' }.rekey do |key|
trimmed = key.to_s.tr('_', '')
trimmed.to_sym
end
# => {:id=>1, :something=>"what?!"}
如果您将哈希传递回重定密钥,它将合并散列,这允许您展平集合。这允许我们在展平哈希时为我们的键添加范围,以避免在合并时覆盖密钥。
people = {
bob: {
name: 'Bob',
toys: [
{ what: 'car', color: 'red' },
{ what: 'ball', color: 'blue' }
]
},
tom: {
name: 'Tom',
toys: [
{ what: 'house', color: 'blue; da ba dee da ba die' },
{ what: 'nerf gun', color: 'metallic' }
]
}
}
people.rekey do |person, person_info|
person_info.rekey do |key|
"#{person}_#{key}".to_sym
end
end
# =>
# {
# :bob_name=>"Bob",
# :bob_toys=>[
# {:what=>"car", :color=>"red"},
# {:what=>"ball", :color=>"blue"}
# ],
# :tom_name=>"Tom",
# :tom_toys=>[
# {:what=>"house", :color=>"blue; da ba dee da ba die"},
# {:what=>"nerf gun", :color=>"metallic"}
# ]
# }