Skip to content

Instantly share code, notes, and snippets.

@mrThe
Created March 12, 2013 15:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mrThe/5143746 to your computer and use it in GitHub Desktop.
Save mrThe/5143746 to your computer and use it in GitHub Desktop.
Hash#path_exists?(*path) method for check paths in hash
class Hash
def path_exists?(*path)
path.flatten.each do |key|
if key.instance_of? Hash
return false unless self[key.keys.first]
return false unless self[key.keys.first].path_exists?(key.values)
elsif key.instance_of? Array
return self.path_exists?(key)
else
return false if self.respond_to?(:keys) && self[key].nil?
end
end
return true
end
end
Example:
hash = {:user => {:old_password => 1, :new_password => '2'}}
hash.path_exists?(:user) #true
hash.path_exists?({:user => [:old_password, :new_password]}) #true
hash.path_exists?({:user => [:old_password]}) #true
hash.path_exists?({:user => [:old_password, :new_password]}, :profile) #false
hash.path_exists?({:people => [:old_password, :new_password]}) #false
hash.path_exists?({:user => [:password]}) #false
hash.path_exists?([:password]) #false
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment