Javatpoint Logo
Javatpoint Logo

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.


Ruby string literals are enclosed within single and double quotes.



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.



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.



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.



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.



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.



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.


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



Ruby string 8

Next TopicRuby arrays

Youtube For Videos Join Our Youtube Channel: Join Now


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Trending Technologies

B.Tech / MCA