<< Previous Page
    

    
      Table of Contents
    

    
      Next Page >>
    
  
06
%q{Literals}
# Number literals
100
=> 100

20000000
=> 20000000

20_000_000
=> 20000000


def heredoc1
# String literals
"a string"
=> a string

'no interpolation'
=> "no interpolation"

a = 'inter'
"#{a}polation"
=> "interpolation"

"\n\t\"" + '"\''
# Regex literals
/[a-z0-9]+/
=> /[a-z0-9]+/

less_readable = /http:\/\/[a-z]+/
=> /http:\/\/[a-z]+/

more_readable = %r{http://[a-z]+}
=> /http:\/\/[a-z]+/
  puts <<MSG
heredoc syntax with
unindented end marker
MSG
MSG
end
# heredoc syntax with an
# unindented end marker
# MSG

def heredoc2
puts <<-MSG
heredoc syntax with an
indented end marker
MSG
end
# heredoc syntax with an
# indented end marker

def heredoc3
puts <<~MSG
heredoc syntax that strips
whitespaces equal to the
first line
MSG
end
#heredoc syntax that strips
#whitespaces equal to the
# first line


<<~INTERPOLATED
#{5}
INTERPOLATED
=> "5\n"

<<~'UNINTERPOLATED'
#{5}
UNINTERPOLATED
a = 5

# Percent literals
%i[big 3d #{a} "]
=> [:big, :"3d", :"\#{a}", :"\""]

%I[big 3d #{a} "]
=> [:big, :"3d", :"5", :"\""]

%w[big 3d #{a} "]
=> ["big", "3d", "\#{a}", "\""]

%W[big 3d #{a} "]
=> ["big", "3d", "5", "\""]

%q(a "b" 'c' #{a})
=> "a \"b\" 'c' \#{a}"

%Q(a "b" 'c' #{a})
=> "a \"b\" 'c' 5"

%(a "b" 'c' #{a})
=> "a \"b\" 'c' 5"

%s(mary's #{a} "twins")
=> :"mary's \#{a} \"twins\""

# Shell commands
`echo hello world`
=> "hello world\n"

%x{echo hello world}
=> "hello world\n"

less_readable = `echo \`ls\``
=> "main.rb Gemfile Gemfile.lock\n"
more_readable = %x{echo `ls`}
=> "main.rb Gemfile Gemfile.lock\n"
=> "\#{5}\n"
<<~`COMMANDHEREDOC`
echo hello
COMMANDHEREDOC
=> "hello\n"
foo(<<-STR1, <<-STR2)
You can pass multiple
STR1
heredocs like this
STR2
06
    
      << Previous Page
    

    
      Table of Contents
    

    
      Next Page >>