Skip to content

Maintenance Ruby 3.4 gets fixes, but no new features. Switch to Ruby 4.0 →

class method

String.new

(?::string source, ?encoding: ::encoding, ?capacity: ::int) -> ::String
String.new(string = '', **opts) → 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 optional argument string and no keyword arguments, returns a copy of string with the same encoding:

Example
String.new('foo')               # => "foo"
String.new('тест')              # => "тест"
String.new('こんにちは')          # => "こんにちは"

(Unlike String.new, a string literal like '' or a here document literal always has script encoding.)

With optional keyword argument encoding, returns a copy of string with the specified encoding; the encoding may be an Encoding object, an encoding name, or an encoding name alias:

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

The given encoding need not be valid for the string’s content, and that validity is not checked:

Example
s = String.new('こんにちは', encoding: 'ascii')
s.valid_encoding? # => false

But the given encoding itself is checked:

Example
String.new('foo', encoding: 'bar') # Raises ArgumentError.

With optional keyword argument capacity, returns a copy of string (or an empty string, if string is not given); the given capacity is advisory only, and may or may not set the size of the internal buffer, which may in turn affect performance:

Example
String.new(capacity: 1)
String.new('foo', capacity: 4096)

Note that Ruby strings are null-terminated internally, so the internal buffer size will be one or more bytes larger than the requested capacity depending on the encoding.

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.3 · 3.2 · 3.1 · 3.0