The string is a collection of characters stored under a variable name.

String a datatype that stores character sequence. It is an object in Ruby.

Let’s see multiple ways to create a String

Ruby String

  • Use String.new constructor
str = String.new('Another string.')

String.new creates a new string every time.

  • Use String literal with a single quote

String created using single or double quotes with literal string assigned.

name='john'
department="Sales"

Above example, Creates a string and assigns it to a variable with implicit type Another way to create a string with single quotes is using the %q notation syntax.

str = %q(single quoted string declaration)

With Single quotes, It is not possible to use escape characters.

  • String literal using double quotes
department="Sales"

Another way to create a string with double quotes is using the %Q syntax.

str = %Q(double-quoted string declaration)

With Double quotes, you can use escape characters.

str = "string with escape character exampl \t \n string example."
  • Create a String with an interpolated String.

Create a string with interpolated syntax by adding a variable.

The interpolated syntax is used only with double-quote strings, not with single-quoted syntax.

name = 'john'
message = "Hello #{name}, Welcome to world."
  • Create Multi-Line String

Multiple ways can do

First, declare a variable by assigning a multiline string.

The string is defined in multiple lines, enclosed in {} Prefix with %Q.

message = %Q{
  line1
  line2
  line 3
}

Another way, using Heredocs syntax.

Prefix with <<~EOS and suffix EOS for a multi-line string

str = <<~EOS
  line1
  line2
  line 3
EOS

Another using <<~END enclose multi-line string with END

str1 = <<~END
  line 1
  line 2
  line 3.

END
puts str1
  • Create a string using concatenation

    One way to create an n string using the concatenation operator +. It creates a new string

str = "test" + " " + " string "
puts str

The second way, using the >> operator

str = "test, " << "example!"

The third way using the concat function

str = "string concatenation ".concat(" example")
  • create an immutable string using freeze

the string can be made an immutable string using the freeze method.

str = "str example".freeze
  • Create a string with other types You can convert other types or symbols into strings using to_s function
number=11
str = number.to_s