简体   繁体   中英

Better way to replace keys of a hash

I want to normalise a Hash 's keys using a normalisation function so that this hash

{"aType" => 1, "b_Type" => 2}

would be converted to

{:atype => 1, :btype => 2}

Here, the normalisation function removes underscores from the keys, downcases them, and makes them symbols.

I wrote the following using map (assume normalize is a normalisation method):

params = params.map {|k,v| {normalize(k) => v}}.inject(:merge)

Is there any better way to do this?

This question is related to a question " How to replace all hash keys having a '.'? ". I want to know the optimal (less verbose or faster) way to do this.

我就是这样做的

Hash[h.map {|k,v| [normalize(k), v] }]

Here's how Rails does it (they extend Hash to make all keys strings in this case, but you could as easily put the method elsewhere).

def stringify_keys!
  keys.each do |key|
    self[key.to_s] = delete(key)
  end
  self
end

Though all of these approaches are reasonable, and there is likely not a substantial readability or performance difference for most uses.

如果您在Rails应用程序中,或者想要引入ActiveSupport,则可以使用ActiveSupport :: HashWithIndifferentAccess ,它允许您使用'key':key来设置或从哈希值中获取值

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM