String, Printing and Symbols


Collapse Content

Strings

A String object holds and manipulates a sequence of characters.

#Single and double quotes are used for Strings
string1 = "hello"
string2 = 'hello'
string1 == string2 #=> true

#Double quotes allow interpolation of variables or code
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"

#Combine strings but not with numbers
"hello " + "world"  #=> "hello world"
"hello " + 3 #=> TypeError: can't convert Fixnum into String
"hello " +3.to_s #=> "hello 3"

#print to the output
print "hello"
print "world"
#=> helloworld

#use puts to add a newline after
puts "hello"
puts "world"
#=> hello
#=> world

Symbols

Symbol objects are immutable, reusable constants represented internally by an integer value. They're often used instead of strings to efficiently convey specific, meaningful values

:pending.class #=> Symbol

status = :pending

status == :pending #=> true

status == 'pending' #=> false

status == :approved #=> false

Challenge

What will the following code print?

name = "jack"
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]