Redis HVALS in Ruby (Detailed Guide w/ Code Examples)

Use Case(s)

The HVALS command in Redis is often used when you need to retrieve all the values associated with a hash. It doesn't return any keys, just the values. This is particularly useful if you're only interested in the values and not the key-value pairs.

In Ruby, you might use this when dealing with collections of data where the keys are known, irrelevant, or unnecessary for processing the held information. For instance, if you stored user attributes in a hash and wanted to collect all attributes without caring about their corresponding keys.

Code Examples

Here's how you can get all values from a hash in Redis using Ruby:

require 'redis' redis = # Set some data in a hash redis.hset("user:1", "name", "John Doe") redis.hset("user:1", "email", "") # Get all values values = redis.hvals("user:1") puts values # prints ["John Doe", ""]

In this example, we set up a new connection to our Redis server, then set two fields (name and email) in a hash representing a user (user:1). We then use hvals to retrieve all the values in the hash.

Best Practices

  • It is recommended to be aware of the size of the hash before using HVALS, as it could potentially return significant amounts of data which causes higher memory usage.
  • Use the HVALS command judiciously, if large hashes are frequently accessed it might be better to iterate through the keys/values using HSCAN, which is more memory efficient and provides a cursor for iteration.

Common Mistakes

  • One common mistake is not checking whether the hash key actually exists before calling HVALS. This will return an empty list if the key does not exist, which might not be the expected behavior in your application. Always ensure that the key exists, or handle the case where it doesn't appropriately.


Q: What happens if the key provided to HVALS isn't a hash? A: Redis will return an error because HVALS only operates on hashes.

Q: How can I get both keys and values from a hash in Ruby? A: You can use the HGETALL command instead of HVALS. It returns an array of [key, value] pairs.

Was this content helpful?

Start building today

Dragonfly is fully compatible with the Redis ecosystem and requires no code changes to implement.