[RUBY] Today's note (backslash notation, output method, here document)

Backslash notation

You can use it in various ways by specifying a character after "".

Specified content Generated characters
\x Generate the x character itself
\n new line
\r Carriage return
\f New Page
\a Bell
\e escape
\s Blank
\b Backspace
\t tab
\v Vertical tab

** * Applies only when enclosed in double quotes "" ", and is recognized as a simple character when enclosed in single quotes" "" **

If you want to check the result of applying \ n etc., output with print or puts. ↓ "Difference in output between p, print and puts" ↓

irb(main):012:0* p "a\nb"
"a\nb"
=> "a\nb"

irb(main):013:0> print "a\nb"
a
b=> nil

irb(main):015:0* puts "a\nb"
a
b
=> nil

Differences in output methods

Method new line Output content construction method Backslash notation
p Line break for each argument inspect method Output as it is
print No line breaks to_s method Output the applied result
puts Line break for each argument to_s method Output the applied result

Here document

I used TEST as the identifier to indicate the end. The second and third lines sandwiched between them are the character strings.

hello = <<TEST
    ohayou
    gozaimasu
TEST

puts hello


#=> 
    ohayou
    gozaimasu
--------------------------------------------------

def hello
    -<<TEST
      ohayou
      gozaimasu
    TEST
end

puts hello

** * Do not write a space etc. before the identifier indicating the end **

Recommended Posts

Today's note (backslash notation, output method, here document)