Skip to content
Formatting
step 1/5

Reading — step 1 of 5

Learn

~1 min readStrings

Three main ways to format strings:

Interpolation (most common):

puts "#{a} + #{b} = #{a + b}"

printf/format (when you need width/precision):

printf "%-10s | %5d\n", "score", 95
s = format("pi = %.4f", 3.14159)   # 'pi = 3.1416'

Heredocs for multi-line strings:

msg = <<~END
    Hello, #{name}!
    Line 2 — note the indentation is stripped.
END

The <<~ (squiggly heredoc) trims the leading whitespace common to all lines. <<-END allows the closing tag to be indented but doesn't trim. Plain <<END requires the closing tag at column zero.

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…