Skip to content
class method

String.new

(?::string source, ?encoding: ::encoding, ?capacity: ::int) -> ::String
String.new(string = ''.encode(Encoding::ASCII_8BIT) , **options) → new_string

Returns a new String object containing the given string.

The options are optional keyword options (see below).

With no argument given and keyword encoding also not given, returns an empty string with the Encoding ASCII-8BIT:

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

With argument string given and keyword option encoding not given, returns a new string with the same encoding as string:

Example
s0 = 'foo'.encode(Encoding::UTF_16)
s1 = String.new(s0)
s1.encoding # => #<Encoding:UTF-16 (dummy)>

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

With keyword option encoding given, returns a string with the specified encoding; the encoding may be an Encoding object, an encoding name, or an encoding name alias:

Example
String.new(encoding: Encoding::US_ASCII).encoding        # => #<Encoding:US-ASCII>
String.new('', encoding: Encoding::US_ASCII).encoding    # => #<Encoding:US-ASCII>
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 its 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 keyword option capacity given, the given value is advisory only, and may or may not set the size of the internal buffer, which may in turn affect performance:

Example
String.new('foo', capacity: 1)    # Buffer size is at least 4 (includes terminal null byte).
String.new('foo', capacity: 4096) # Buffer size is at least 4;
                                  # may be equal to, greater than, or less than 4096.
See also .json_create .try_convert #% also in 4.1 · 3.4 · 3.3 · 3.2 · 3.1 · 3.0