Skip to content

End of Life Ruby 3.0 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →

class method

String.new

String.new(string = '') → new_string
String.new(string = '', encoding: encoding) → new_string
String.new(string = '', capacity: size) → new_string

Returns a new String that is a copy of string.

With no arguments, returns the empty string with the Encoding ASCII-8BIT:

Example
s = String.new
s # => ""
s.encoding # => #<Encoding:ASCII-8BIT>

With the single String argument string, returns a copy of string with the same encoding as string:

Example
s = String.new("Que veut dire \u{e7}a?")
s # => "Que veut dire \u{e7}a?"
s.encoding # => #<Encoding:UTF-8>

Literal strings like "" or here-documents always use script encoding, unlike String.new.

With keyword encoding, returns a copy of str with the specified encoding:

Example
s = String.new(encoding: 'ASCII')
s.encoding # => #<Encoding:US-ASCII>
s = String.new('foo', encoding: 'ASCII')
s.encoding # => #<Encoding:US-ASCII>

Note that these are equivalent:

Example
s0 = String.new('foo', encoding: 'ASCII')
s1 = 'foo'.force_encoding('ASCII')
s0.encoding == s1.encoding # => true

With keyword capacity, returns a copy of str; the given capacity may set the size of the internal buffer, which may affect performance:

Example
String.new(capacity: 1) # => ""
String.new(capacity: 4096) # => ""

The string, encoding, and capacity arguments may all be used together:

Example
String.new('hello', encoding: 'UTF-8', capacity: 25)
See also .try_convert #% also in 4.1 · 4.0 · 3.4 · 3.3 · 3.2 · 3.1