redis-rb guide (Ruby)

Connect your Ruby application to a Redis database

redis-rb is the Ruby client for Redis. The sections below explain how to install redis-rb and connect your application to a Redis database.

redis-rb requires a running Redis server. See here for Redis Open Source installation instructions.

Install

To install redis-rb, run the following command:

gem install redis

Connect and test

Connect to localhost on port 6379:

Language: Ruby
Run in browser
Foundational: Connect to a Redis server and establish a client connection
Ctrl+Enter to run
require 'redis'
r = Redis.new

Store and retrieve a simple string.

Language: Ruby
Run in browser
Foundational: Set and retrieve string values using SET and GET commands
Ctrl+Enter to run
r.set 'foo', 'bar'
value = r.get('foo')
puts value

Store and retrieve a dict.

Language: Ruby
Run in browser
Foundational: Store and retrieve hash data structures using HSET and HGETALL
Ctrl+Enter to run
r.hset 'user-session:123', 'name', 'John'
r.hset 'user-session:123', 'surname', 'Smith'
r.hset 'user-session:123', 'company', 'Redis'
r.hset 'user-session:123', 'age', 29

hash_value = r.hgetall('user-session:123')
puts hash_value

Close the connection when you're done.

Language: Ruby
Run in browser
Foundational: Properly close a Redis client connection to release resources
Ctrl+Enter to run
r.close()

More information

The GitHub repository for redis-rb has a set of examples and further information about using redis-rb.

RATE THIS PAGE
Back to top ↑