Ruby strings could be understood as a group of characters. A string could be of length 1 (one character), but its usually longer. A string is always defined in double qoutes.

This means a string variable in ruby could hold text: words, sentences, books

Programming languages have variables. These variables have a data type
A variable could be of the data type string.

Related Course: Learn Ruby On Rails For Web Development

String example

Introduction

A String object in Ruby stores and operates any sequence of one or more bytes, usually representing characters that represent human language.

The simplest string is enclosed in single quotation marks (single quote characters).The text within the quotation mark is the value of the string:

1
'This is a string for Ruby programs'

If you need to use single quote characters within a single-quoted string, you need to use a backslash in the single-quoted string so that the Ruby interpreter does not think that the single-quoted character terminates the string:

1
'Won\'t you read Randy\'s book?'

String variable

In the example below we use ruby to print text.
First define a string variable, then print the variable.

1
2
3
4
#!/usr/bin/ruby

str = String.new("This is a string example")
puts "#{str}"

Save as strings-example.rb. Then run with

1
ruby strings-example.rb

This should output:

ruby string example

Multiple lines

Generally there are 2 ways to print multiple lines.

Method 1. call display function x times,
Method 2. use the newline character inside the string

Both of these are common in programming.

1
2
3
4
5
6
7
8
#!/usr/bin/ruby

# method 1: multiple calls
puts "Hello"
puts "World"

# method 2: newline characters
puts "Hello World"

Ruby strings

In double quotation marks strings, we can use the # {} pound sign and the curly bracket to calculate the value of the expression:

Embedded variables in string:

1
2
3
4
5
6
#!/usr/bin/ruby
# -*- coding: UTF-8 -*-

name1 = "Juan"
name2 = "Maria"
puts "Names #{name1}, #{name2} ?"

You can do mathematical operations in string.

1
2
3
4
5
6
7
#!/usr/bin/ruby
# -*- coding: UTF-8 -*-

x, y, z = 12, 36, 72
puts "x = #{ x }"
puts "x + y = #{ x + y }"
puts "x + y + z = #{ (x + y + z)/3 }"

This outputs:

1
2
3
x = 12
x + y = 48
x + y + z = 40

Exercises

  1. Create a program with multiple string variables
  2. Create a program that holds your name in a string.