Hash#has_value?

Added in v1.8.7 · Updated March 13, 2026 · Hash Methods
ruby hash enumerable

The has_value? method checks whether a hash contains a specific value. It’s the value-checking counterpart to has_key?.

Syntax

hash.has_value?(value)   # => true or false
hash.value?(value)       # => true or false (alias)

Parameters

ParameterTypeDefaultDescription
valueObjectRequiredThe value to search for in the hash

Return Value

Returns true if the hash contains the given value, false otherwise.

Description

Ruby’s Hash class provides two methods for checking value existence:

  • has_value? — The primary method name.
  • value? — A shorter alias that does the same thing.

Both methods search through all hash values and return a boolean. They handle any Ruby object as a value, including nil.

This method is useful when you need to verify that a particular value exists in a hash, regardless of which key it’s associated with.

Examples

Basic usage

hash = { name: "Alice", age: 30, city: "London" }

hash.has_value?("Alice")   # => true
hash.has_value?(100)       # => false
hash.has_value?(30)        # => true
hash.has_value?(nil)       # => false

Using the alias

config = { theme: "dark", debug: false }

config.value?("dark")    # => true
config.value?(true)      # => false

Checking for nil values

data = { placeholder: nil, valid: "something" }

data.has_value?(nil)     # => true - finds the nil value
data.has_value?("")      # => false

With different value types

mixed = { id: 1, name: "Test", active: true, tags: [:a, :b] }

mixed.has_value?(1)           # => true (integer)
mixed.has_value?("Test")     # => true (string)
mixed.has_value?(:a)         # => false (not the array)
mixed.has_value?([:a, :b])   # => true (array)

Performance Note

This method iterates through all values in the hash, making it O(n) complexity. For large hashes or frequent lookups, this is slow.

If you find yourself calling has_value? repeatedly, consider these alternatives:

  • Invert the hash if you need to look up keys by value: hash.invert
  • Use a Set for large collections of unique values
  • Re-think the data structure — if you’re searching for values often, a hash may not be the right choice

See Also