Skip to content
instance method · added in Ruby 3.2

String#dedup

() -> self
-self → frozen_string

Alias of #-@

Returns a frozen string equal to self.

The returned string is self if and only if all of the following are true:

  • self is already frozen.

  • self is an instance of String (rather than of a subclass of String)

  • self has no instance variables set on it.

Otherwise, the returned string is a frozen copy of self.

Returning self, when possible, saves duplicating self; see Data deduplication.

It may also save duplicating other, already-existing, strings:

Example
s0 = 'foo'
s1 = 'foo'
s0.object_id == s1.object_id       # => false
(-s0).object_id == (-s1).object_id # => true

Note that method -@ is convenient for defining a constant:

Example
FileName = -'config/database.yml'

While its alias dedup is better suited for chaining:

Example
'foo'.dedup.gsub!('o')

Related: see Freezing/Unfreezing.

Ruby version changes

  1. 3.2
See also #-@ #crypt #delete #count also in 4.1 · 3.4 · 3.3 · 3.2