instance method · added in Ruby 3.2
String#dedup
() -> self
-self → frozen_string
string.c
View on GitHub ↗
static VALUE
str_uminus(VALUE str)
{
if (!BARE_STRING_P(str) && !rb_obj_frozen_p(str)) {
str = rb_str_dup(str);
}
return rb_fstring(str);
}
Alias of #-@
Returns a frozen string equal to self.
The returned string is self if and only if all of the following are true:
-
selfis already frozen. -
selfis an instance of String (rather than of a subclass of String) -
selfhas 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
-
3.2
-
String#deduphas been added as an alias toString#-@. [Feature #18595]
-