Hash#keys
hash.keys Returns:
Array · Added in v1.8 · Updated March 14, 2026 · Hash Methods ruby stdlib hash
Hash#keys returns a new array containing all the keys from the hash, in insertion order. This method is useful when you need to iterate over all keys or when you need a list of keys for set operations.
Syntax
hash.keys
Examples
Basic key extraction
user = { name: "Alice", email: "alice@example.com", age: 30 }
user.keys
# => [:name, :email, :age]
Iteration with keys
config = { host: "localhost", port: 3000, ssl: true }
config.keys.each do |key|
puts "#{key}: #{config[key]}"
end
# Output:
# host: localhost
# port: 3000
# ssl: true
Converting to a set
h1 = { a: 1, b: 2 }
h2 = { b: 3, c: 4 }
# Find common keys
(h1.keys & h2.keys)
# => [:b]
Common Patterns
Check if a key exists
data = { name: "Bob", active: true }
data.keys.include?(:name)
# => true
data.keys.include?(:missing)
# => false
However, using Hash#has_key? or Hash#include? is more efficient for this purpose.
Transform keys
hash = { first_name: "John", last_name: "Doe" }
hash.keys.map(&:to_s)
# => ["first_name", "last_name"]
Sorting keys
scores = { bob: 95, alice: 87, charlie: 92 }
scores.keys.sort
# => [:alice, :bob, :charlie]
Get all values as well
h = { x: 10, y: 20 }
h.keys
# => [:x, :y]
h.each_value.to_a
# => [10, 20]
Edge Cases
Empty hash
{}.keys
# => []
Integer keys
{ 1 => "one", 2 => "two" }.keys
# => [1, 2]
Mixed key types
{ "name" => "Alice", :age => 25, 3 => "three" }.keys
# => ["name", :age, 3]
See Also
- Hash#has_key? — Checks if a key exists
- Hash#has_value? — Checks if a value exists
- Hash#each_key — Iterates over each key