liveBook · Manning

String literal

As explained in The Well-Grounded Rubyist, Fourth Edition

A string literal is Ruby source syntax that directly represents a String value.

A string literal is Ruby source syntax that directly produces a String value. Double-quoted and single-quoted forms look similar, but they differ in interpolation and escape processing. section 8.1.1 section 7.5.1

Choose the notation according to the behavior and layout the string needs:

  • Use double quotes when #{...} interpolation or escapes such as \n and \t should be interpreted. section 8.1.1
  • Use single quotes when interpolation should remain literal; backslashes generally remain ordinary characters, except when escaping the quote or another backslash. section 8.1.1
  • Use percent notation such as %q{}, %Q{}, or %{} when a different delimiter makes embedded quotation marks easier to read. section 8.1.1
  • Use heredocs for multiline strings, including SQL, indented text, method arguments, and strings with optional interpolation behavior. section 8.1.1

Interpolation and truthiness

puts "Two plus two is #{2 + 2}." puts 'Two plus two is #{2 + 2}.' The first line prints 4; the second prints the interpolation marker literally. A string literal evaluates to itself and is truthy in an if test, including an empty string. section 8.1.1 section 7.5.1

class RubyWelcomeWagon
  def hyphen_message
    <<-EOM
      Welcome to the world of Ruby!
      In this method, the EOM doesn't have to be flush left!
         EOM
  end

  def squiggly_message
    <<~EOM
      Welcome to the world of Ruby!
      We're happy you're here!
    EOM
  end

end

Compare <<-EOM and <<~EOM heredocs to see how terminator placement and indentation affect the resulting multiline string. section 8.1.1

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Explains quoting, interpolation, escaping, percent notation, heredocs, and conditional behavior through runnable examples rather than exhaustive reference detail.
Examples
Uses irb snippets, quotation contrasts, percent-delimited strings, SQL heredocs, indented heredocs, and conditional tests.
What it assumes
Assumes basic Ruby expressions and conditional syntax while demonstrating string behavior from simple quoted examples onward.
What you can do after
Apply it via irb to write quoted and multiline strings, control interpolation, and choose appropriate escaping or delimiters.
How it connects
Connects string literals with string interpolation, escape sequences, heredocs, expressions, conditional statements, and Boolean values.

Also explained in

Compare how 2 books explain string literal →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Well-Grounded Rubyist, Fourth Edition. The section links point to the parts of the book it draws on.