Posts for: #Hash

Hash deep search

I’m back and I wanna share those simple snippets with you:

~

class Hash def deep_has_key?(key) self.has_key?(key) || any? {|k, v| v.deep_has_key?(key) if v.is_a? Hash} end alias :deep_include? :deep_has_key? alias :deep_key? :deep_has_key? alias :deep_member? :deep_has_key?

def deep_has_value?(value) self.has_value?(value) || any? {|k,v| v.deep_has_value?(value) if v.is_a? Hash} end alias :deep_value? :deep_has_value? end

Example:
{:a => {:c => 'c'}, :b =>{:d => {:e => 'e'}}}.deep_has_key?(:e) # => true {:a => {:c => 'c'}, :b =>{:d => {:e => 'e'}}}.deep_has_key?(:z) # => false

{:a => {:c => ‘c’}, :b =>{:d => {:e => ’e’}}}.deep_has_value?(’e’) # => true {:a => {:c => ‘c’}, :b =>{:d => {:e => ’e’}}}.deep_has_value?(‘z’) # => false

[]

Javascript HashMap

Reading around i’ve discovered that Javascript associative arrays returns unpredictable results, i.e. length param is not correctly handled.

Array object should be used only with a numeric index and best way to avoid this problem is to use Object.

But, if I wanna put more objects in my object?

Of course i can do this with previous method, but i don’t like it :-P. So, i’ve written a 100% OOP class, that use Prototype and it simulate a java HashMap.

[]