---
source_url: https://www.pubnub.com/docs/sdks/ruby
title: Ruby API & SDK Docs 6.0.2
updated_at: 2026-05-20T11:08:14.062Z
sdk_name: PubNub Ruby SDK
sdk_version: 6.0.2
---

> Documentation Index
> For a curated overview of PubNub documentation, see: https://www.pubnub.com/docs/llms.txt
> For the full list of all documentation pages, see: https://www.pubnub.com/docs/llms-full.txt


# Ruby API & SDK Docs 6.0.2

PubNub Ruby SDK, use the latest version: 6.0.2

Install:

```bash
gem install pubnub@6.0.2
```

This guide walks you through a simple "Hello, World" application that demonstrates the core concepts of PubNub:

* Setting up a connection
* Sending messages
* Receiving messages in real-time

## Overview

This guide will help you get up and running with PubNub in your Ruby application. You'll learn how to integrate the PubNub Ruby SDK to build real-time features into your applications.

The PubNub Ruby SDK provides a simple API for building real-time applications with features like:

* Publish/subscribe messaging
* Presence detection (online/offline status)
* Storage and playback
* Access control
* Push notifications

## Prerequisites

Before we dive in, make sure you have:

* A basic understanding of Ruby
* Ruby 2.7 or later installed
* Bundler for managing dependencies (optional)
* A PubNub account (we'll help you set this up!)

## Setup

### Get your PubNub keys

First things first – you'll need your PubNub keys to get started. Here's how to get them:

* [Sign in](https://admin.pubnub.com/#/login) or [create an account](https://admin.pubnub.com/#/signup) on the PubNub Admin Portal.
* Create a new app (or use an existing one).
* Find your publish and subscribe keys in the app's dashboard.

When you create an app, PubNub automatically generates a keyset. You can use the same keyset for development and production, but we recommend separate keysets for each environment to improve security and management.

### Install the SDK

:::note SDK version
Always use the latest SDK version to have access to the newest features and avoid security vulnerabilities, bugs, and performance issues.
:::

Install the PubNub Ruby SDK using RubyGems:

```bash
gem install pubnub
```

Alternatively, if you're using Bundler:

1. Create a `Gemfile` in your project directory:

```ruby
# Gemfile
source 'https://rubygems.org'

gem 'pubnub', '~> 6.0.2'
```

1. Then run:

```bash
bundle install
```

#### Source code

Clone the [GitHub repository](https://github.com/pubnub/ruby):

```bash
git clone https://github.com/pubnub/ruby
```

For a list of supported platforms, see the [platform support documentation](https://www.pubnub.com/docs/sdks/ruby/platform-support).

## Steps

### Initialize PubNub

First, create a new `app.rb` file and add the following code to initialize the PubNub client.

Make sure to replace the demo keys with your own publish and subscribe keys from the Admin Portal.

```ruby
require 'pubnub'

# Initialize PubNub
pubnub = Pubnub.new(
  subscribe_key: 'demo',
  publish_key: 'demo',
  user_id: 'myUniqueUserId',
  ssl: true
)

puts "PubNub initialized with user_id: #{pubnub.user_id}"
```

This creates a new PubNub instance with your keys and a unique user ID. The `ssl: true` parameter ensures your connections are secure.

For more information, refer to the [Configuration](https://www.pubnub.com/docs/sdks/ruby/api-reference/configuration) section of the SDK documentation.

### Set up event listeners

Next, set up listeners to handle incoming messages, presence events, and connection status updates:

```ruby
# Define callbacks for different event types
callback = Pubnub::SubscribeCallback.new(
  message: ->(envelope) {
    puts "MESSAGE: #{envelope.result[:data][:message]['text']}"
  },
  presence: ->(envelope) {
    puts "PRESENCE: #{envelope.result[:data]}"
  },
  status: ->(envelope) {
    if envelope.status[:error]
      puts "ERROR: #{envelope.status[:category]}"
    else
      puts "STATUS: #{envelope.status[:category]}"
    end
  }
)

# Add the listener to the PubNub instance
pubnub.add_listener(callback: callback)
```

The message listener receives and processes incoming messages from subscribed channels. The presence listener handles presence events, such as when users join or leave channels. The status listener provides information about the connection status and any errors.

For more information, refer to the [Listeners](https://www.pubnub.com/docs/sdks/ruby/api-reference/configuration#event-listeners) section of the SDK documentation.

### Create a subscription

Now, subscribe to a channel to start receiving messages:

```ruby
# Subscribe to a channel
pubnub.subscribe(
  channels: ['my_channel'],
  with_presence: true
)

puts "Subscribed to 'my_channel'"
```

This code subscribes to the channel `my_channel`. The `with_presence: true` parameter enables presence events, allowing you to see when users join or leave the channel.

For more information, refer to the [Subscribe](https://www.pubnub.com/docs/sdks/ruby/api-reference/publish-and-subscribe#subscribe) section of the SDK documentation.

### Publish messages

After subscribing, you can publish messages to the channel.

When you publish a message to a channel, PubNub delivers that message to everyone who is subscribed to that channel.

A message can be any type of JavaScript Object Notation (JSON)-serializable data (such as objects, arrays, integers, strings) that is smaller than 32 KiB.

```ruby
# Define a message to publish
message = { text: 'Hello world!' }

# Publish the message
pubnub.publish(
  channel: 'my_channel',
  message: message
) do |envelope|
  if envelope.status[:error]
    puts "Publish Error: #{envelope.status[:error]}"
  else
    puts "Message Published! Timetoken: #{envelope.result[:timetoken]}"
  end
end
```

This publishes a simple message with the text "Hello world!" to the channel `my_channel`. The callback handles the response, confirming the message was published or reporting any errors.

### Run the app

Now that you've set up all the components, let's put them together and run the application:

1. Save your file as `app.rb`.
2. Run the application with:

```bash
ruby app.rb
```

You should see output similar to:

```text
PubNub initialized with user_id: myUniqueUserId
Subscribed to 'my_channel'
Waiting for messages... (Press Ctrl+C to exit)
STATUS: ack
MESSAGE: Hello world!
PRESENCE: {message: {"action" => "join", "uuid" => "myUniqueUserId", "timestamp" => 1743511468, "precise_timestamp" => 1743511468385, "occupancy" => 4}, subscribed_channel: "my_channel-pnpres", actual_channel: "my_channel-pnpres", publish_time_object: {timetoken: "17435114683856450", region_code: 23}, message_meta_data: {"pn_action" => "join", "pn_channel" => "my_channel", "pn_ispresence" => 1, "pn_occupancy" => 4, "pn_precise_timestamp" => 1743511468385, "pn_timestamp" => 1743511468, "pn_uuid" => "myUniqueUserId"}, presence_event: "join", presence: {uuid: "myUniqueUserId", timestamp: 1743511468, state: nil, occupancy: 4}}
Completed the demonstration
```

This indicates that:

1. PubNub was successfully initialized with your user ID.
2. You successfully subscribed to 'my_channel'.
3. The application is waiting for messages and events.
4. You received a status acknowledgement ('ack') from the PubNub network.
5. You received the message with "Hello world!" that was published to the channel.
6. You received a presence event showing that your user joined the channel, along with detailed metadata about the event.
7. The demonstration completed after running for the specified time.

## Complete example

Here's the complete working example that puts everything together:

```ruby
require 'pubnub'

# Initialize PubNub
pubnub = Pubnub.new(
  subscribe_key: 'demo',
  publish_key: 'demo',
  user_id: 'myUniqueUserId',
  ssl: true
)

puts "PubNub initialized with user_id: #{pubnub.user_id}"

# Define callbacks for different event types
callback = Pubnub::SubscribeCallback.new(
  message: ->(envelope) {
    puts "MESSAGE: #{envelope.result[:data][:message]['text']}"
  },
  presence: ->(envelope) {
    puts "PRESENCE: #{envelope.result[:data]}"
  },
  status: ->(envelope) {
    if envelope.status[:error]
      puts "ERROR: #{envelope.status[:category]}"
    else
      puts "STATUS: #{envelope.status[:category]}"
    end
  }
)

# Add the listener to the PubNub instance
pubnub.add_listener(callback: callback)

# Subscribe to a channel
pubnub.subscribe(
  channels: ['my_channel'],
  with_presence: true
)

puts "Subscribed to 'my_channel'"

# Define a message to publish
message = { text: 'Hello world!' }

# Publish the message
pubnub.publish(
  channel: 'my_channel',
  message: message
) do |envelope|
  if envelope.status[:error]
    puts "Publish Error: #{envelope.status[:error]}"
  else
    puts "Message Published! Timetoken: #{envelope.result[:timetoken]}"
  end
end

# Keep the program running to receive messages
# In a real application, you might use an event loop or framework
puts "Waiting for messages... (Press Ctrl+C to exit)"
sleep 5  # Wait for 5 seconds to see the results
puts "Completed the demonstration"
```

### Troubleshooting

If you don't see the expected output, here are some common issues and how to fix them:

| Issue | Possible Solutions |
| --- | --- |
| No connection message | Check your internet connection., Verify your publish and subscribe keys are correct., Make sure you're not behind a firewall blocking PubNub's connections. |
| Message not received | Double-check that you're subscribed to the correct channel., Verify that the message was actually sent (check for any error messages)., Make sure you're waiting long enough for the message to be delivered., Ensure you set up the message listener correctly. |
| Ruby errors | Ensure you've installed the PubNub gem correctly., Check that you're using a compatible version of Ruby (2.7+)., Make sure all imports are correct., Verify your code matches the examples exactly. |

## Next steps

Great job! 🎉 You've successfully created your first PubNub Ruby application. Here are some exciting things you can explore next:

### Advanced features

* Try out [Presence](https://www.pubnub.com/docs/sdks/ruby/api-reference/presence) to track online/offline status.
* Implement [Message Persistence](https://www.pubnub.com/docs/sdks/ruby/api-reference/storage-and-playback) to store and retrieve messages.
* Use [Access Manager](https://www.pubnub.com/docs/sdks/ruby/api-reference/access-manager) to secure your channels.
* Explore [Channel Groups](https://www.pubnub.com/docs/sdks/ruby/api-reference/channel-groups) to organize your channels.
* Implement [Push Notifications](https://www.pubnub.com/docs/sdks/ruby/api-reference/mobile-push) for mobile applications.

### Real examples

* Explore our [GitHub repository](https://github.com/pubnub/ruby) for more code samples.

### More help

* Check out the [Ruby SDK reference documentation](https://www.pubnub.com/docs/sdks/ruby/api-reference/configuration) for detailed API information.
* Visit the [support portal](https://support.pubnub.com/) for additional resources.
* Ask the AI assistant (the looking glass icon at the top of the page) for help.

## Terms in this document

* **Publish Key** - A unique identifier that allows your application to send messages to PubNub channels. It's part of your app's credentials and should be kept secure.
* **PubNub** - PubNub is a real-time messaging platform that provides APIs and SDKs for building scalable applications. It handles the complex infrastructure of real-time communication, including: Message delivery and persistence, Presence detection, Access control, Push notifications, File sharing, Serverless processing with Functions and Events & Actions, Analytics and monitoring with BizOps Workspace, AI-powered insights with Illuminate.
* **Subscribe Key** - A unique identifier that allows your application to receive messages from PubNub channels. It's part of your app's credentials and should be kept secure.