---
source_url: https://www.pubnub.com/docs/sdks/ruby/api-reference/publish-and-subscribe
title: Publish/Subscribe API for Ruby SDK
updated_at: 2026-06-16T12:52:31.238Z
sdk_name: PubNub Ruby SDK
sdk_version: 6.1.0
---

> 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


# Publish/Subscribe API for Ruby SDK

PubNub Ruby SDK, use the latest version: 6.1.0

Install:

```bash
gem install pubnub@6.1.0
```

PubNub delivers messages worldwide in less than 30 ms. Send a message to one recipient or broadcast to thousands of subscribers.

For higher-level conceptual details on publishing and subscribing, refer to [Connection Management](https://www.pubnub.com/docs/general/setup/connection-management) and to [Publish Messages](https://www.pubnub.com/docs/general/messages/publish).

## Publish

`publish()` sends a message to all channel subscribers. PubNub replicates the message across its points of presence and delivers it to all subscribed clients on that channel.

:::warning ObjectNode
The new Jackson parser does not recognize JSONObject. Use ObjectNode instead.
:::

###### Prerequisites and limitations

* You must [initialize PubNub](https://www.pubnub.com/docs/sdks/ruby/api-reference/configuration#configuration) with the `publishKey`.
* You don't have to be subscribed to a channel to publish to it.
* You cannot publish to multiple channels simultaneously.

###### Security

Secure messages with Transport Layer Security (TLS) or Secure Sockets Layer (SSL) by setting `ssl` to `true` during [initialization](https://www.pubnub.com/docs/sdks/ruby/api-reference/configuration#configuration). You can also [encrypt](https://www.pubnub.com/docs/sdks/ruby/api-reference/configuration#crypto_module) messages.

###### Message data

The message can contain any JavaScript Object Notation (JSON)-serializable data (objects, arrays, integers, strings). Avoid special classes or functions. Strings can include any UTF‑8 characters.

:::warning Don't JSON serialize
You should not JSON serialize the `message` and `meta` parameters when sending signals, messages, or files as the serialization is automatic. Pass the full object as the message/meta payload and let PubNub handle everything.
:::

###### Size

The maximum message size is 32 KiB. This includes the escaped character count and the channel name. Aim for under 1,800 bytes for optimal performance.

If your message exceeds the limit, you'll receive a `Message Too Large` error. To learn more or calculate payload size, see [Message size limits](https://www.pubnub.com/docs/general/messages/publish#message-size-limit).

:::tip Need larger messages?
Our platform is optimized for payloads up to 32 KiB. PubNub supports larger messages, but increasing the limit requires a verification of compatibility with your use case.
Talk to [our team](https://www.pubnub.com/company/contact-sales/) to discuss increasing the message size limit for your use case.
:::

###### Publish rate

You can publish as fast as bandwidth allows. There is a [soft throughput limit](https://www.pubnub.com/docs/general/setup/limits) because messages may drop if subscribers can't keep up.

For example, publishing 200 messages at once may cause the first 100 to drop if a subscriber hasn't received any yet. The in-memory queue stores only 100 messages.

###### Custom message type

You can optionally provide the `custom_message_type` parameter to add your business-specific label or category to the message, for example `text`, `action`, or `poll`.

###### Best practices

* Publish to a channel serially (not concurrently).
* Verify a success return code (for example, `[1,"Sent","136074940..."]`).
* Publish the next message only after a success return code.
* On failure (`[0,"blah","<timetoken>"]`), retry.
* Keep the in-memory queue under 100 messages to avoid drops.
* Throttle bursts to meet latency needs (for example, no more than 5 messages per second).

### Method(s)

To `Publish a message` you can use the following method(s) in the Ruby SDK:

```ruby
publish(
    channel: String,
    message: Object,
    store: Boolean,
    compressed: Boolean,
    publish_key: String,
    http_sync: Boolean,
    custom_message_type: String,
    meta: Object,
    callback: Lambda
)
```

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| channel | String | Yes |  | Specify the `channel` ID to `publish` the messages. |
| message | Object | Yes |  | Serializable `object` that has defined `#to_json` method. |
| store | Boolean | Optional |  | Specifies if `message` should be stored for `history`.Default `true`. |
| compressed | Boolean | Optional |  | Specifies if `message` should be compressed.Default `false`. |
| publish_key | String | Optional |  | Specifies the required `publish_key` to use to send messages to a `channel` ID. |
| http_sync | Boolean | Optional |  | Default `false`. Method will be executed `asynchronously` and will return future, to get it's `value` you can use `value` method. If set to `true`, method will return array of envelopes (even if there's only one `envelope`). For `sync` methods `Envelope` object will be returned. |
| custom_message_type | String | Optional |  | A case-sensitive, alphanumeric string from 3 to 50 characters describing the business-specific label or category of the message. Dashes `-` and underscores `_` are allowed. The value cannot start with special characters or the string `pn_` or `pn-`. Examples: `text`, `action`, `poll`. |
| meta | Object | Optional |  | A JSON-serializable object that provides additional context information for the message. |
| callback | Lambda | Optional |  | `Callback` that will be called for each `envelope`. For `async` methods future will be returned, to retrieve `value` `Envelope` object you have to call `value` method (thread will be locked until the `value` is returned). |

### Sample code

#### Publish a message to a channel

:::tip Reference code
This example is a self-contained code snippet ready to be run. It includes necessary imports and executes methods with console logging. Use it as a reference when working with other examples in this document.
:::

```ruby
require 'pubnub'

def publish_message(pubnub)
  pubnub.publish(
    channel: 'my_channel',
    message: { text: 'Hi!' },
    custom_message_type: 'text-message'
  ) do |envelope|
    puts "Publish status: #{envelope.status[:code]}"
  end
end

def main
  # Configuration for PubNub instance
  pubnub = Pubnub.new(
    subscribe_key: ENV.fetch('SUBSCRIBE_KEY', 'demo'),
    publish_key: ENV.fetch('PUBLISH_KEY', 'demo'),
    user_id: 'myUniqueUserId'
  )

  # Publish a message
  publish_message(pubnub)
  sleep 1 # Allow time for the async operation to complete
end

if __FILE__ == $0
  main
end
```

:::note Subscribe to the channel
Before running the above publish example, either using the [Debug Console](https://www.pubnub.com/docs/console/) or in a separate script running in a separate terminal window, [subscribe to the same channel](#subscribe) that is being published to.
:::

### Rest response from server

The function returns the following formatted response:

```json
[1, "Sent", "13769558699541401"]
```

### Other examples

#### Publish a JSON serialized message

```ruby
pubnub.publish(
    message: {
        key: {
            inner_key: :value
        }
    },
    custom_message_type: 'text-message',
    channel: :whatever,
    meta: {
        sender_uuid: 'user123-uuid',
        priority: 'high',
        location: 'office'
    }
)
```

#### Skip message from storage

```ruby
pubnub.publish(message: 'Not gonna store that', store: false)
```

## Fire

The fire endpoint sends a message to Functions event handlers and [Illuminate](https://www.pubnub.com/docs/illuminate/business-objects/external-data-sources). The message goes directly to handlers registered on the target channel and triggers their execution. The handler can read the request body. Messages sent via `fire()` aren't replicated to subscribers and aren't stored in history.

### Method(s)

To `Fire a message` you can use the following method(s) in the Ruby SDK:

```ruby
fire(
    channel: channel,
    message: message,
    compressed: compressed,
    publish_key: publish_key,
    http_sync: http_sync,
    callback: callback
)
```

| Parameter | Description |
| --- | --- |
| `channel` *Type: String | Specify the `channel` ID to `publish` the messages. |
| `message` *Type: Object | Serializable `object` that has defined `#to_json` method. |
| `compressed`Type: Boolean | Specifies if `message` should be compressed.Default `false`. |
| `publish_key`Type: String | Specifies the required `publish_key` to use to send messages to a `channel` ID. |
| `http_sync`Type: Boolean | Default `false`. Method will be executed `asynchronously` and will return future, to get it's `value` you can use `value` method. If set to `true`, method will return array of envelopes (even if there's only one `envelope`). For `sync` methods `Envelope` object will be returned. |
| `callback`Type: Lambda accepting one parameter | `Callback` that will be called for each `envelope`. For `async` methods future will be returned, to retrieve `value` `Envelope` object you have to call `value` method (thread will be locked until the `value` is returned). |

### Sample code

#### Fire a message to a channel

```ruby
pubnub.fire(
    channel: 'my_channel',
    message: {
        text: 'Hi!'
    }
) do |envelope|
    puts envelope.status
end
```

## Signal

The `signal()` function sends a signal to all subscribers of a channel.

By default, signals are limited to a message payload size of `64` bytes. This limit applies only to the payload, and not to the URI or headers. If you require a larger payload size, please [contact support](https://www.pubnub.com/docs/mailto:support@pubnub.com).

### Method(s)

To `Signal a message` you can use the following method(s) in the Ruby SDK:

```ruby
pubnub.signal(
    message: Object,
    channel: String,
    compressed: Boolean,
    custom_message_type: String
)
```

| Parameter | Description |
| --- | --- |
| `message` *Type: Object | Serializable `object` that has defined `#to_json` method. |
| `channel` *Type: String | Specify the `channel` ID to `send` the messages. |
| `compressed`Type: Boolean | Specifies if `message` should be compressed. Default `false`. |
| `custom_message_type`Type: String | A case-sensitive, alphanumeric string from 3 to 50 characters describing the business-specific label or category of the message. Dashes `-` and underscores `_` are allowed. The value cannot start with special characters or the string `pn_` or `pn-`. Examples: `text`, `action`, `poll`. |

### Sample code

#### Signal a message to a channel

```ruby
pubnub.signal(
    channel: 'foo',
    message: {
        msg: 'Hello Signals'
    },
    custom_message_type: 'text-message'
);
```

### Rest response from server

The function returns the following formatted response:

```javascript
[1, "Sent", "13769558699541401"]
```

## Subscribe

### Receive messages

Your app receives messages and events via event listeners. The event listener is a single point through which your app receives all the messages, signals, and events that are sent in any channel you are subscribed to.

For more information about adding a listener, refer to the [Event Listeners](https://www.pubnub.com/docs/sdks/ruby/api-reference/configuration#event-listeners) section.

:::note No built-in event throttling
The PubNub SDK delivers every incoming event to your listener as it arrives — there is no built-in throttling or rate-limiting on the subscriber side. If you need to control how often your application processes events, wrap your listener callback with a throttle or debounce utility from your language or framework ecosystem.
To reduce the number of messages delivered to your client in the first place, use [Subscribe Filters](https://www.pubnub.com/docs/general/channels/subscribe-filters) to filter messages server-side before they reach your listener.
:::

### Description

This function causes the client to create an open TCP socket to the PubNub Real-Time Network and begin listening for messages on a specified `channel` ID. To subscribe to a `channel` ID the client must send the appropriate `subscribe_key` at initialization. By default a newly subscribed client will only receive messages published to the channel after the `subscribe()` call completes.

:::tip Connectivity notification
You can be notified of connectivity via the `envelope.status`. By waiting for the `envelope.status` to return before attempting to publish, you can avoid a potential race condition on clients that subscribe and immediately publish messages before the subscribe has completed.
:::

Using Ruby SDK, if a client becomes disconnected from a channel, it can automatically attempt to reconnect to that channel and retrieve any available messages that were missed during that period by setting `restore` to `true`. By default a client will attempt to reconnect after exceeding a `320` second connection timeout.

:::warning Unsubscribing from all channels
**Unsubscribing** from all channels, and then **subscribing** to a new channel Y is not the same as subscribing to channel Y and then unsubscribing from the previously-subscribed channel(s). Unsubscribing from all channels resets the last-received `timetoken` and thus, there could be some gaps in the subscription that may lead to message loss.
:::

### Method(s)

To `Subscribe to a channel` you can use the following method(s) in the Ruby SDK:

```ruby
subscribe(
    channels: channels,
    channel_groups: group,
    presence: presence,
    presence_callback: presence_callback,
    with_presence: with_presence,
    http_sync: http_sync,
    callback: callback
)
```

| Parameter | Description |
| --- | --- |
| `channels`Type: String, Symbol, Array | Specify the `channels` to `subscribe` to. It is possible to specify multiple channels as an array. It is possible to `subscribe` to wildcard channels. |
| `channel_groups`Type: String, Symbol, Array | Specifies the `group` to `subscribe` to. It is possible to specify multiple groups as an array. |
| `presence`Type: String, Symbol, Array | Specifies the `channel` ID to `presence` `subscribe` to. It is possible to specify multiple channels as an array. |
| `presence_callback`Type: Lambda accepting one argument | `Callback` that is called for each `presence` event from wildcard `subscribe`. Works only with `http_sync` set to `true`. |
| `with_presence`Type: Boolean | Subscribes to all `presence` channels of channels listed in channels parameter. For information on how to receive presence events and what those events are, refer to [Presence Events](https://www.pubnub.com/docs/general/presence/presence-events#subscribe-to-presence-channel). |
| `http_sync`Type: Boolean | Default `false`. Method will be executed `asynchronously` and will return future, to get it's `value` you can use `value` method. If set to `true`, method will return array of envelopes (even if there's only one `envelope`). For `sync` methods they will return array of Envelopes - `envelope` object for each message. |
| `callback`Type: Lambda accepting one parameter | `Callback` that is called for each retrieved `message`. Works only with `http_sync` set to `true`. |

:::note Event listeners
The response of the subscription is handled by Listener. Please see the [Listeners section](https://www.pubnub.com/docs/sdks/ruby#add-event-listeners) for more details.
:::

### Sample code

Subscribe to a channel:

```ruby
# Subscribe to channel 'my_channel'.
pubnub.subscribe(
    channels: :my_channel
)
```

### Rest response from server

The output below demonstrates the response format to a successful call:

```json
[[], "Time Token"]
```

### Other examples

#### Subscribing to multiple channels

It's possible to subscribe to more than one channel using the [Multiplexing](https://www.pubnub.com/docs/general/channels/subscribe#channel-multiplexing) feature. The example shows how to do that using an array to specify the channel names.

:::note Alternative subscription methods
You can also use [Wildcard Subscribe](https://www.pubnub.com/docs/general/channels/subscribe#wildcard-subscribe) and [Channel Groups](https://www.pubnub.com/docs/general/channels/subscribe#channel-groups) to subscribe to multiple channels at a time. To use these features, the *Stream Controller* add-on must be enabled on your keyset in the [Admin Portal](https://admin.pubnub.com).
:::

```ruby
# Subscribe to channels (with presence) and groups
pubnub.subscribe(
    channels: ['debug', 'info', 'warn'],
    channel_groups: ['ruby_group', 'jruby_group', 'rbx_group'],
    presence: ['debug', 'info', 'warn']
)
# You will be subscribed to channels: debug, info, warn, debug-pnpres, info-pnpres and warn-pnpres
# and to groups: ruby_group, jruby_group, rbx_group.
```

#### Subscribing to a Presence channel

:::warning Requires Presence
This method requires that the Presence add-on is [enabled](https://support.pubnub.com/hc/en-us/articles/360051974791-How-do-I-enable-add-on-features-for-my-keys-) for your key in the [Admin Portal](https://admin.pubnub.com/). For information on how to receive presence events and what those events are, refer to [Presence Events](https://www.pubnub.com/docs/general/presence/presence-events#subscribe-to-presence-channel).
:::

For any given channel there is an associated Presence channel. You can subscribe directly to the channel by appending `-pnpres` to the channel name. For example the channel named `my_channel` would have the presence channel named `my_channel-pnpres`.

```ruby
# Subscribes to room0, room0-pnpres, room1, room1-pnpres, room2, room2-pnpres
pubnub.subscribe(
    channels: ['room0', 'room1', 'room2'],
    with_presence: true
)
```

#### Sample Responses

#### Join event

```json
{
    "action": "join",
    "timestamp": 1345546797,
    "uuid": "175c2c67-b2a9-470d-8f4b-1db94f90e39e",
    "occupancy": 2
}
```

##### Leave event

```json
{
    "action" : "leave",
    "timestamp" : 1345549797,
    "uuid" : "175c2c67-b2a9-470d-8f4b-1db94f90e39e",
    "occupancy" : 1
}
```

##### Timeout event

```json
{
    "action": "timeout",
    "timestamp": 1345549797,
    "uuid": "76c2c571-9a2b-d074-b4f8-e93e09f49bd",
    "occupancy": 0
}
```

##### State change event

```json
{
    "action": "state-change",
    "uuid": "76c2c571-9a2b-d074-b4f8-e93e09f49bd",
    "timestamp": 1345549797,
    "data": {
        "isTyping": true
    }
}
```

##### Interval event

```json
{
    "action":"interval",
    "timestamp":1474396578,
    "occupancy":2
}
```

When a channel is in interval mode with `presence_deltas` `pnconfig` flag enabled, the interval message may also include the following fields which contain an array of changed UUIDs since the last interval message.

* joined
* left
* timedout

For example, this interval message indicates there were 2 new UUIDs that joined and 1 timed out UUID since the last interval:

```json
{
    "action" : "interval",
    "occupancy" : <# users in channel>,
    "timestamp" : <unix timestamp>,
    "joined" : ["uuid2", "uuid3"],
    "timedout" : ["uuid1"]
}
```

If the full interval message is greater than `30 KB` (since the max publish payload is `∼32 KiB`), none of the extra fields will be present. Instead there will be a `here_now_refresh` boolean field set to `true`. This indicates to the user that they should do a `hereNow` request to get the complete list of users present in the channel.

```json
{
    "action" : "interval",
    "occupancy" : <# users in channel>,
    "timestamp" : <unix timestamp>,
    "here_now_refresh" : true
}
```

#### Wildcard subscribe to channels

:::note Requires Stream Controller add-on
This method requires that the *Stream Controller* add-on is enabled for your key in the [Admin Portal](https://admin.pubnub.com/) (with Enable Wildcard Subscribe checked). Read the [support page](https://support.pubnub.com/hc/en-us/articles/360051974791-How-do-I-enable-add-on-features-for-my-keys-) on enabling add-on features on your keys.
:::

Wildcard subscribes allow the client to subscribe to multiple channels using wildcard. For example, if you subscribe to `a.*` you will get all messages for `a.b`, `a.c`, `a.x`. The wildcarded `*` portion refers to any portion of the channel string name after the `dot (.)`.

```ruby
# Subscribe to wildcard channel 'ruby.*' (make sure you have wildcard subscribe enabled in your pubnub admin console!)
# specify two different callbacks for messages from channels and presence events in channels.
pubnub.subscribe(
    channels: 'ruby.*'
)
```

:::note Wildcard grants and revokes
Only one level (`a.*`) of wildcarding is supported. If you grant on `*` or `a.b.*`, the grant will treat `*` or `a.b.*` as a single channel named either `*` or `a.b.*`. You can also revoke permissions from multiple channels using wildcards but only if you previously granted permissions using the same wildcards. Wildcard revokes, similarly to grants, only work one level deep, like `a.*`.
:::

#### Subscribing with state

:::warning Requires Presence
This method requires that the Presence add-on is [enabled](https://support.pubnub.com/hc/en-us/articles/360051974791-How-do-I-enable-add-on-features-for-my-keys-) for your key in the [Admin Portal](https://admin.pubnub.com/). For information on how to receive presence events and what those events are, refer to [Presence Events](https://www.pubnub.com/docs/general/presence/presence-events#subscribe-to-presence-channel).
:::

:::note Required User ID
Always set the `UserId` to uniquely identify the user or device that connects to PubNub. This `UserId` should be persisted, and should remain unchanged for the lifetime of the user or the device. If you don't set the `UserId`, you won't be able to connect to PubNub.
:::

```ruby
require 'pubnub'

PUBKEY = 'demo'
SUBKEY = 'demo'

pubnub = Pubnub.new(
    subscribe_key: SUBKEY,
    publish_key: PUBKEY,
    ssl: true
)

callback = Pubnub::SubscribeCallback.new(
    message: ->(envelope) {
        puts "MESSAGE: #{envelope.result[:data]}"
    },
    presence: ->(envelope) {
        puts "PRESENCE: #{envelope.result[:data]}"
    }
)

pubnub.add_listener(callback: callback)
subs = pubnub.subscribe(channels: 'public', with_presence: true)

subs.add_observer do
    pubnub.set_state(channels: 'public', state: {key: 'val'}) do |env|
        if env.error?
            # handle error
        else
            # success
        end
    end
end
```

#### Subscribe to a channel group

:::note Requires Stream Controller add-on
This method requires that the *Stream Controller* add-on is enabled for your key in the [Admin Portal](https://admin.pubnub.com/). Read the [support page](https://support.pubnub.com/hc/en-us/articles/360051974791-How-do-I-enable-add-on-features-for-my-keys-) on enabling add-on features on your keys.
:::

```ruby
# Subscribe to group
pubnub.subscribe(
    channel_groups: 'ruby_group'
)
```

#### Subscribe to the Presence channel of a channel group

:::note Requires Stream Controller and Presence add-ons
This method requires both the *Stream Controller* and *Presence* add-ons are enabled for your key in the [Admin Portal](https://admin.pubnub.com/). Read the [support page](https://support.pubnub.com/hc/en-us/articles/360051974791-How-do-I-enable-add-on-features-for-my-keys-) on enabling add-on features on your keys.
:::

```ruby
pubnub = Pubnub.new(
    subscribe_key: :demo,
    publish_key: :demo
)

callback = Pubnub::SubscribeCallback.new(
    message:  ->(_envelope) {
    },
    presence: ->(envelope) {
        puts "PRESENCE: #{envelope.result[:data]}"
    },
    status:   ->(_envelope) {
    }
)

pubnub.add_listener(callback: callback)

pubnub.presence(channel_groups: 'family')
```

##### Subscribe sync

:::note Loop
The loop will exit when there is no subscribed channel left, closing the program in turn.
:::

```ruby
require 'pubnub'
pubnub = Pubnub.new(
    subscribe_key: :demo,
    publish_key: :demo
)

pubnub.subscribe(channels: :whatever)
while pubnub.subscribed_channels.size > 0 do
    sleep 1
end
```

## Unsubscribe

When subscribed to a single channel, this function causes the client to issue a `leave` from the `channel` and close any open socket to the PubNub Network. For multiplexed channels, the specified `channel`(s) will be removed and the socket remains open until there are no more channels remaining in the list.

:::warning Unsubscribing from all channels
**Unsubscribing** from all channels, and then **subscribing** to a new channel Y is not the same as subscribing to channel Y and then unsubscribing from the previously-subscribed channel(s). Unsubscribing from all channels resets the last-received `timetoken` and thus, there could be some gaps in the subscription that may lead to message loss.
:::

### Method(s)

To `Unsubscribe from a channel` you can use the following method(s) in the Ruby SDK:

```ruby
unsubscribe(
    channels: channels,
    channel_groups: group,
    http_sync: http_sync,
    callback: callback
)
```

| Parameter | Description |
| --- | --- |
| `channels`Type: Symbol, String | Specify the `channels` to `unsubscribe` from. (Required if `channel_groups` is not specified) |
| `channel_groups`Type: Symbol, String | Specify the `channel_groups` to `unsubscribe` from. (Required if `channels` is not specified) |
| `http_sync`Type: Boolean | Default `false`. Method will be executed `asynchronously` and will return future, to get it's `value` you can use `value` method. If set to `true`, method will return array of envelopes (even if there's only one `envelope`). For `sync` methods `Envelope` object will be returned. |
| `callback`Type: Lambda accepting one parameter | `Callback` that will be called for each `envelope`. For `async` methods future will be returned, to retrieve `value` `Envelope` object you have to call `value` method (thread will be locked until the `value` is returned). |

### Sample code

Unsubscribe from a channel:

```ruby
pubnub.unsubscribe(
    channel: 'my_channel'
) do |envelope|
    puts envelope.status
end
```

### Response

```ruby
#<Pubnub::Envelope
    @status = {
        :code => 200,
        :operation => :leave,
        :category => :ack,
        :error => false,
        # [...]
    },
    # [...]
>
```

### Other examples

#### Unsubscribing from multiple channels

:::note Requires Stream Controller add-on
This method requires that the *Stream Controller* add-on is enabled for your key in the [Admin Portal](https://admin.pubnub.com/). Read the [support page](https://support.pubnub.com/hc/en-us/articles/360051974791-How-do-I-enable-add-on-features-for-my-keys-) on enabling add-on features on your keys.
:::

```ruby
pubnub.unsubscribe(
    channel: ['chan1','chan2','chan3']
) do |envelope|
    puts envelope.status
end
```

```ruby
pubnub.unsubscribe(
    channel: ['chan1','chan2','chan3']
) do |envelope|
    puts envelope.result[:data][:messages]
end
```

##### Example response

```json
{
    "action" : "leave"
}
```

#### Unsubscribing from a channel group

```ruby
pubnub.leave(channel_group: "cg1") do |envelope|
    puts envelope.status
end
```

#### Unsubscribing from multiple channel groups

:::note Requires Stream Controller add-on
This method requires that the *Stream Controller* add-on is enabled for your key in the [Admin Portal](https://admin.pubnub.com/). Read the [support page](https://support.pubnub.com/hc/en-us/articles/360051974791-How-do-I-enable-add-on-features-for-my-keys-) on enabling add-on features on your keys.
:::

```ruby
pubnub.leave(group: ["cg1", "cg2"]) do |envelope|
    puts envelope
end
```

## Terms in this document

* **Access Manager** - A cryptographic, token-based permission administrator that allows you to regulate clients' access to PubNub resources, such as channels, channel groups, and user IDs.
* **Action** - The type of activity (procedure) to execute when a condition is satisfied (for example, sending a message).
* **Billing alert notification** - A means of informing a user that a billing alert has been triggered. Before notifications can happen, a billing alert must be triggered first.
* **Business Object** - A container for data fields and metrics that defines aggregations and data sources.
* **Channel** - A pathway for sending and receiving messages between devices, created automatically when you first use it, that can handle any number of users and messages for different communication needs, like 1-1 text chats, group conversations, and other data streaming.
* **Channel pattern** - A way to group and analyze channel data to track performance metrics like message counts and user engagement over time with PubNub Insights.
* **Condition** - A requirement that must be satisfied or evaluated to true for an action to be executed. Input in a decision table.
* **Cryptor** - An implementation of a specific cryptographic algorithm used for data encryption/decryption that adheres to a standard interface.
* **Dashboard** - A collection of widgets (charts) that give an overview of the metrics one is evaluating.
* **Data fields** - Data you want Illuminate to track. These can be quantitative (measures), like "Number" or "Timestamp" or qualitative (dimensions) values, like "String" that can be used to categorize and segment data. Data fields can be aggregated and calculated.
* **Decision** - A collection (or decision table) of conditions and actions. When conditions are satisfied, the corresponding actions are triggered as per defined rules.
* **End Customer** - A customer of a PubNub partner. End customers do not have direct access to the Admin Portal. Instead, they interact with PubNub products—such as Illuminate—through the partner’s portal, where PubNub services are embedded. They can create PubNub objects only within this partner-provided environment.
* **Entity** - A subscribable object within a PubNub SDK that allows you to perform context-specific operations.
* **Listener** - A function or objectthat reacts to events or messages, like new chat messages or connection updates, letting your app respond in real-time.
* **Mapped/Unmapped** - Whether the data source for a data field has been defined or the action has been configured.
* **MCP Server** - A Model Context Protocol server that coordinates communication and synchronization between AI agents, clients, or services, such as Cursor IDE and Windsurf.
* **Message** - A unit of data transmitted between clients or between a client and a server in PubNub, containing information such as text, binary data, or structured data formats like JSON. Messages are sent over channels and can be tracked for delivery and read status.
* **Metric** - What exactly is evaluated using measures and dimensions (collectively called data fields), as well as aggregation functions.
* **Module** - A Functions v1 container that groups related functions for configuration and deployment on an app’s keysets.
* **Origin** - The subdomain used to establish a connection to the PubNub network that allows your application's traffic to appear like it's coming from your own domain.
* **Package** - A Functions v2 container that groups Functions, tracks Revisions, and is deployed to keysets.
* **Partner** - A PubNub customer who resells PubNub products, such as Illuminate, to their own customers. Partners have access to the Admin Portal, enabling them to create and manage PubNub objects for themselves or on behalf of their end customers.
* **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.
* **Push token** - A device identifier issued by a push provider (APNs or FCM) used to register a device for receiving mobile push notifications.
* **Rule** - A definition (row in a decision table) stating which action should be triggered for which condition.
* **Service Integration** - A machine identity that represents a program or service consuming the Admin API, scoped to your account and authenticated using expirable API keys with configurable permissions.
* **Signal** - A non-persistent message limited to 64 bytes designed for high-volume usecases where the the most recent data is relevant, like GPS location updates.
* **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.
* **Timetoken** - A unique identifier for each message that represents the number of 100-nanosecond intervals since January 1, 1970, for example, 16200000000000000.
* **Trigger details** - A set of predefined criteria for a given billing alert. When met, billing alert notifications are generated.
* **User** - An individual or entity that interacts with a system, application, or service. In PubNub, a user typically refers to someone who sends or receives messages through the platform, identified by a unique user ID or username.
* **User ID** - UTF-8 encoded, unique string of up to 92 characters used to identify a single client (end user, device, or server) that connects to PubNub.
* **Vibe Coding** - A way to build applications in an intuitive, relaxed, and improvisational manner, using AI tools and natural language descriptions.