Ruby String Basics

Strings are a core part of the Ruby language and are constantly used when programming in Ruby.

They can be either single or double quoted:

'strings with single quotes'
"strings with double quotes"

You can print out strings:

print 'some words'
# => some words

puts "even more words"
# => even more words

Strings are commonly stored in a variable:

string = "Ham, jam, spam, pam, maam"

puts string
# => Ham, jam, spam, pam, maam

Strings are concatenated like this:

puts "123" + " " + "Main " + "Street"
# => 123 Main Street

Ruby strings are commonly concatenated using the `+` operator.

this = 'Shoe'
that = 'box'

those = this + that
# "Shoebox"

Ruby can also concatenate with the `<<` operator.

one = "1"
two = "2"
three = "3"

count = ""
count << one # 1
count << two # 12
count << three # 123
count # 123

String Interpolation is often used in Ruby to construct sentences. Within double-quoted strings, you can embed Ruby expressions using `#{}`.

title = "Dr"
name = "Frank"

puts "I would like to see #{title} #{name}!"
# => I would like to see Dr Frank!

You will often see this used in Ruby on Rails views to display information from one or more models.

"You have purchased #{@product.name} for $#{@product.price}."

Ruby strings can be [compared](/blog/2023/06/30/Comparing-Strings-in-Ruby) using comparison operators (`==`, `<`, `>`, etc.).

"bird" == "bird" # true
"bird" == "cat" # false

String comparison in Ruby is case sensitive:

"nope" == "NOPE" # false
"noWay" == "NoWaY" # false
"noWay".downcase == "NoWaY".downcase # true

Ruby supports multiline strings.

string_of_great_length = <<~WRD
  This string
  is
  very
  long.
WRD

# "This string\nis\nvery\nlong.\n"


Posted

in

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *