Key and value checks for Ruby arrays and hashes
Posted on 23 May 2012
Array and Hash classes in ruby have a basic functionality for the keys and values presence checks. However if you need some more advanced features, like testing if array contains all or any of the keys, you'll probably write a inline method. Having more frienly methods and ability to not repeat yourself is a huge plus.
Here is a small snippet with core class extensions for Array and Hash:
class Array
def include_all?(values)
(values - self).empty?
end
def include_any?(values)
(self & values).any?
end
end
class Hash
def include_all?(keys)
self.keys.include_all?(keys)
end
def include_any?(keys)
self.keys.include_any?(keys)
end
end
Examples:
[1,2,3].include_any?([1,2]) # => true
[1,2,3].include_any?([4,5,6]) # => false
[1,2,3].include_all?([1,2,3,4]) # => true
[1,2,3].include_all?([1,2]) # => false
For hashes:
({'a' => 1, 'b' => 2}.include_any?(['a', 'b', 'c'])) # => true
({'a' => 1, :b => 2}.include_any?(['a', 'b', 'c'])) # => true
({'a' => 1, 'b' => 2}.include_all?(['a','b', 'c'])) # => true
({'a' => 1, 'b' => 2}.include_all?(['c'])) # => false