Hash values through query like nested keys

How to get “x[y][z]” out of a hash ?

This made life with our form helpers a lot easier, since they take normal or nested keys <-> name of the input and prefilled value through params.

Any alternative is appreciated, since its pretty complex/hacky, the name is weird too …
(a simple to_query.split(‘=’)).inject… can work too, but would stringify all values and keys)

Usage

{'x'=>{'y'=>{'z'=>1}}}.value_from_nested_key('x[y][z]') == 1

Code

class Hash
  # {'x'=>{'y'=>{'z'=>1}}.value_from_nested_key('x[y][z]') => 1
  def value_from_nested_key(key)
    if key.to_s.include?('[')
      match, first, nesting = key.to_s.match(/(.+?)\[(.*)\]/).to_a
      value = self[first]
      nesting.split('][').each do |part|
        return nil unless value.is_a?(Hash)
        value = value[part]
      end
      value
    else
      self[key]
    end
  end
end

2 thoughts on “Hash values through query like nested keys

  1. I tried something like…

    def keys_array
      @keys_array = []
    end
    
    def deep_print_keys(hash_or_array)
      if hash_or_array.is_a? Hash
        hash_or_array.each_pair do |k,v|
          @keys_array << k
          if v.is_a? Hash
            deep_print_keys(v)
          else v.is_a? Array
            v.each{|element| deep_print_keys(element) }
          end
        end
      end
    end
    
    keys_array
    
    deep_print_keys(xml_hash)
    
    @keys_array.uniq.sort.each{|key| puts key}
    
  2. that will give me all keys of a given hash, and does nothing for an array?
    what i am trying to do is getting the nested key ‘x[y][z]’ from a hash like {‘x’=>{‘y’=>{‘z’=>3}}}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s