class Hash

Public Instance Methods

deep_delete(deep_key) click to toggle source
# File lib/cucumber/helpers/core_ext.rb, line 16
def deep_delete(deep_key)
  path_keys = deep_key.split('.')
  final_key = path_keys.pop

  sub_obj = self
  path_keys.each do |k|
    if k.match(/^(.+)\[(\d+)\]$/)
      sub_obj = sub_obj[$1][$2.to_i]
    else
      sub_obj = sub_obj[k]
    end
  end

  sub_obj.delete(final_key)
end
deep_key(deep_key) click to toggle source
# File lib/cucumber/helpers/core_ext.rb, line 2
def deep_key(deep_key)
  sub_obj = self
  deep_key.split('.').each do |k|
    if k.match(/^(.+)\[(\d+)\]$/)
      sub_obj = sub_obj[$1][$2.to_i]
    else
      sub_obj = sub_obj[k]
    end
  end
  sub_obj
rescue
  nil
end
deep_set(deep_key, value) click to toggle source
# File lib/cucumber/helpers/core_ext.rb, line 32
def deep_set(deep_key, value)
  path_keys = deep_key.split('.')
  final_key = path_keys.pop

  sub_obj = self
  path_keys.each do |k|
    if k.match(/^(.+)\[(\d+)\]$/)
      sub_obj = sub_obj[$1][$2.to_i]
    else
      sub_obj[k] ||= {}
      sub_obj = sub_obj[k]
    end
  end

  if final_key.match(/^(.+)\[(\d+)\]$/)
    sub_obj[$1][$2.to_i] = value
  else 
    sub_obj[final_key] = value
  end
end
flat_hash(separator = ".") click to toggle source

Collapses any nested hashes, converting the keys to delimited strings.

For example, the hash ‘{ “address” => { “line1” => …, “line2” => … } }` will be converted to `{ “address.line1” => …, “address.line2” => … }`. The keys produced are compatible with the `deep_*` functions on hash, so this can provide a convenient way to iterate through values of a hash.

Note that this function is lossy - if two nested hashes would result in the same keys then only one will be preserved.

# File lib/cucumber/helpers/core_ext.rb, line 62
def flat_hash(separator = ".")
  each_with_object({}) do |(k, v), result|
    if v.is_a?(Hash)
      v.flat_hash(separator).each do |k2, v2|
        result["#{k}#{separator}#{k2}"] = v2
      end
    else
      result[k] = v
    end
  end
end