Strings & Symbols


Collapse Content

This tutorial is based in part on LearnXinYminutes (by davefp and others) and is licensed under the Creative Commons Attribution-ShareAlike 3.0 License. See learnXinYminutes.com.

Strings

A String object holds and manipulates a sequence of characters. They are declared with single or double quotes.

word1 = "hello"
word2 = 'hello'

word1 and word2 are equal to each other:

word1 == word2 #=> true

Double quotes allow interpolation of variables or code. This means you can use a special syntax in the string to evaluate code or insert the value of certain variables:

placeholder = "string interpolation"
"I can use #{placeholder} in double-quoted strings"
#=> "I can use string interpolation in double-quoted strings"
'I cannot use #{placeholder} in single-quotes strings'
#=> => "I cannot use \#{placeholder} in single-quotes strings"

+ is used to concatenate strings together but cannot combine strings and numbers:

"hello " + "world"  #=> "hello world"
"hello " + 3 #=> TypeError: can't convert Fixnum into String
"hello " +3.to_s #=> "hello 3"

Strings in Ruby can be accessed and edited like arrays:

str = "cat"
str[0] #=> "c"
str[0] = "b"
str #=> "bat"

Symbols

Symbols in Ruby are marked with a colon :, like in :word. Unlike Ruby Strings, Symbols objects are immutable, which means they cannot be changed. Ruby strings are used to store messages, and symbols are usually used to identify items.

:pending.class #=> Symbol    
status = :pending    
status == :pending #=> true    
status == 'pending' #=> false   #symbols are not the same as strings
status == :approved #=> false

Symbols are also often used as the keys in hashes.

Challenge

What will the following code print?

name = "jim"
puts "hello #{name}" + ' hello #{name}'

Please sign in or sign up to submit answers.

Alternatively, you can try out Learneroo before signing up.

Challenge

You will be given a word as input. Print a message "Hello [word]!" on its own line. (Replace [name] with the given name).

Please sign in or sign up to submit answers.

Alternatively, you can try out Learneroo before signing up.

Contact Us
Sign in or email us at [email protected]