[Ruby] Today’s memo (backslash notation, output method, here document)

1 minute read

Backslash notation

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

Specified content Generated characters
\x Generates the character x itself
\n Line feed
\r Carriage turn
\f Page break
\a Bell
\e Escape
\s blank
\b Backspace
\t Tab
\v Vertical tab

** * Applicable only when enclosed in double quotes “””, and recognized as simple characters when enclosed in single quotes “”” **

If you want to check the result of applying \n etc., output with print or puts. ↓ “Output difference 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

Output method differences

| Method | Line feed | Method for constructing output contents | Backslash notation | |:—————–|——————:|:——— ———:|:——————:| | p | Line feed for each argument | inspect method | Output as is | | print | No line breaks | to_s method | Output applied results | | puts | Line feed for each argument | to_s method | Output applied results |

Heredoc

TEST was used for the identifier that indicates the end. The second and third lines sandwiched between them form the character string.

hello = <<TEST
    ohayou
    gozaimasu
TEST

puts hello


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

def hello
    -<<TEST
      ohayou
      gozaimasu
    TEST
end

puts hello

** * Do not describe spaces etc. before the identifier that indicates the end **

Tags:

Updated: