Hash#include?
The include? method checks whether a hash contains a specific key. It’s one of several key-checking methods available on Ruby’s Hash class.
Syntax
hash.include?(key) # => true or false
Aliases
The include? method has three aliases:
| Method | Description |
|---|---|
has_key? | Same behavior, most explicit |
key? | Same behavior, shorter |
member? | Same behavior, older alias |
include? | Original method name |
All four methods check whether the given object exists as a key in the hash.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
key | Object | Required | The key to search for in the hash |
Return Value
Returns true if the key exists in the hash, false otherwise.
Description
Ruby’s Hash class provides four methods for checking key existence:
include?— The original method namehas_key?— The most explicit aliaskey?— The shortest aliasmember?— An older alias
All four do exactly the same thing: they check whether the argument is a key in the hash. They use the hash’s internal lookup mechanism, making them O(1) for average case.
This method is useful when you need to verify that a particular key exists before accessing or modifying its value.
Examples
Basic usage
hash = { name: "Alice", age: 30, city: "London" }
hash.include?(:name) # => true
hash.include?(:age) # => true
hash.include?(:country) # => false
Using the aliases
config = { theme: "dark", debug: false }
config.has_key?(:theme) # => true
config.key?(:debug) # => true
config.member?(:missing) # => false
With different key types
mixed_keys = { "string_key" => 1, :symbol_key => 2, 42 => 3 }
mixed_keys.include?("string_key") # => true
mixed_keys.include?(:symbol_key) # => true
mixed_keys.include?(42) # => true
mixed_keys.include?("missing") # => false
Checking before access
options = { timeout: 30, retries: 3 }
if options.include?(:timeout)
puts "Timeout is set to #{options[:timeout]}"
end
With nil as a key
sparse = { nil => "null value", "key" => 42 }
sparse.include?(nil) # => true
sparse.include?("key") # => true
sparse.include?("not_there") # => false
Performance Note
The include? method (and its aliases) use the hash’s internal lookup mechanism, making them O(1) on average. This is much faster than iterating through all keys.
If you find yourself calling include? or has_key? repeatedly, consider whether the data structure fits your access pattern.
See Also
hash-has-key— The explicit alias for include?hash-has-value— For checking values instead of keyshash-keys— Returns all keys in the hashhash-values— Returns all values in the hashhash-merge— Merge hashes together