Home » Ruby Strings

Ruby Strings

Ruby string object holds and manipulates an arbitary sequence of bytes, typically representing characters. They are created using String::new or as literals.


Quotes

Ruby string literals are enclosed within single and double quotes.

Example:

Output:

Ruby string 1


Accessing string elements

You can access Ruby string elements in different parts with the help of square brackets []. Within square brackets write the index or string.

Example:

Output:

Ruby string 2


Multiline string

Writing multiline string is very simple in Ruby language. We will show three ways to print multi line string.

  • String can be written within double quotes.
  • The % character is used and string is enclosed within / character.
  • In heredoc syntax, we use << and string is enclosed within word STRING.

Example:

Output:

Ruby string 3


Variable Interpolation

Ruby variable interpolation is replacing variables with values inside string literals. The variable name is put between #{ and } characters inside string literal.

Example:

Output:

Ruby string 4


Concatenating Strings

Ruby concatenating string implies creating one string from multiple strings. You can join more than one string to form a single string by concatenating them.

There are four ways to concatenate Ruby strings into single string:

  • Using plus sign in between strings.
  • Using a single space in between strings.
  • Using << sign in between strings.
  • Using concat method in between strings.

Example:

Output:

Ruby string 5


Freezing Strings

In most programming languages strings are immutable. It means that an existing string can’t be modified, only a new string can be created out of them.

In Ruby, by default strings are not immutable. To make them immutable, freeze method can be used.

Example:

Output:

Ruby string 6

In the above output, we have made the string immutable by using freeze method. Last line is commented as no string can’t be modified any further.

By uncommenting the last line, we’ll get an error as shown in the below output.

Output:

Ruby string 7


Comparing Strings

Ruby strings can be compared with three operators:

  • With == operator : Returns true or false
  • With eql? Operator : Returns true or false
  • With casecmp method : Returns 0 if matched or 1 if not matched

Example:

Output:

Ruby string 8


Next TopicRuby arrays

You may also like