开发者

Is there an elegant way to remove a specific key from a hash and it's sub-hashes in Ruby

Lets say I have a hash which may contain hashes.

params: { :action => "index", :controller => "home", 
          :secret => "I love Jeff Atwood",
          :user => {name => "Steve", secret => "I steal Joel's pants"}}

Is there an elegant 开发者_JAVA技巧way to traverse the hash and remove all the "secret" keys I come across including the subhashes. (The hashes are not restricted so no way to know what the hashes may contain in advance.)

I know I could do

params.delete(:secret)

but that wouldn't get the secret from the 'user' hash.


I don't think there is a built in method for this so a simple recursive method along the following lines is one solution:

def recursive_delete(hash, to_remove)
  hash.delete(to_remove)
  hash.each_value do |value|
    recursive_delete(value, to_remove) if value.is_a? Hash
  end
end

With your example data:

h = { :action => "index", :controller => "home", :secret => "I love Jeff Atwood",
          :user => {:name => "Steve", :secret => "I steal Joel's pants"}}

recursive_delete(h, :secret)

puts h.inspect

Gives:

{:controller=>"home", :user=>{:name=>"Steve"}, :action=>"index"}

Note that this solution works in place i.e. it is modifying the original Hash, not returning a new Hash with the requested key excluded.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜