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.

Download Free Ruby Ebook

String example

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"

Exercises

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