Recursive hash operation in Ruby which fowards a block

in code


Recursive hash operations were annoying as heck to puzzle out because, you know, functions aren’t just functions in Ruby: You have functions and procs/lambdas, all of which have subtle differences. Like a regular function cannot be passed as a block.

Well, whatever, I had a problem where I had to walk, reject-from and then compact a bunch of deeply-nested YAML files. This worked:

refine Hash
  def recursive_reject(block = Proc.new)
    delete_if do |key, value|
      value.recursive_reject block if value.is_a? Hash
      block.call key, value
    end
  end
end

And behold:

hash.recursive_reject { |key, value| key == :ponies || value == 'sparkles' }

A post by Joe Yates gave me the insight to get this done.



Blog Silence

in me

Run Clare 2019 Race Series

in running


Your email address will not be published. Required fields are marked *