Hash#values
hash.values Returns:
Array · Added in v1.8 · Updated March 14, 2026 · Hash Methods ruby hash stdlib
Hash#values returns a new array containing all the values from the hash, in insertion order. This method is useful when you need to extract just the values or iterate over them.
Syntax
hash.values
Examples
Basic value extraction
user = { name: "Alice", email: "alice@example.com", age: 30 }
user.values
# => ["Alice", "alice@example.com", 30]
Iteration with values
scores = { alice: 95, bob: 87, charlie: 92 }
scores.values.each do |score|
puts "Score: #{score}"
end
# Output:
# Score: 95
# Score: 87
# Score: 92
Convert to a set for unique values
inventory = { apples: 5, oranges: 3, bananas: 5, grapes: 7 }
Set.new(inventory.values)
# => #<Set: {5, 3, 7}>
Common Patterns
Check if a value exists
data = { name: "Bob", status: "active" }
data.values.include?("active")
# => true
data.values.include?("pending")
# => false
However, using Hash#value? or Hash#has_value? is more efficient for this purpose.
Transform values
prices = { coffee: 5, tea: 3, milk: 2 }
prices.values.map { |p| p * 1.1 }
# => [5.5, 3.3, 2.2]
Sum numeric values
cart = { apples: 3, bananas: 5, oranges: 2 }
cart.values.sum
# => 10
Get values in sorted order (when comparable)
temps = { monday: 72, tuesday: 68, wednesday: 75 }
temps.values.sort
# => [68, 72, 75]
Extract both keys and values separately
h = { a: 1, b: 2, c: 3 }
keys = h.keys
values = h.values
keys.zip(values)
# => [[:a, 1], [:b, 2], [:c, 3]]
Edge Cases
Empty hash
{}.values
# => []
Mixed value types
{ name: "Alice", age: 25, active: true }.values
# => ["Alice", 25, true]
Duplicate values
{ a: 1, b: 2, c: 1 }.values
# => [1, 2, 1]
Values with nil
{ a: nil, b: 2, c: nil }.values
# => [nil, 2, nil]
Performance Considerations
Hash#values creates a new array each time it’s called. For very large hashes, this can be memory-intensive. If you only need to iterate over values, consider using Hash#each_value instead:
# Memory efficient iteration
large_hash.each_value { |value| process(value) }
See Also
- Hash#keys — Returns all keys
- Hash#value? — Checks if a value exists
- Hash#has_value? — Alias for value?