[ruby] About here documents

Here document

By enclosing the long sentence with an identifier, you can save the long sentence as well.

irb(main):033:0> puts = <<hia
irb(main):034:0" ruby
irb(main):035:0" most like
irb(main):036:0" Programming language
irb(main):037:0" hia
=> "ruby\nmost like\nProgramming language\n"

First of all, I will explain Start label with an identifier called hia in a variable called puts on the first line If you enter the identifier that is the end label on the 4th line, the contents of the 2nd and 3rd lines will be stored in the variable puts. The stored contents are displayed on the 6th line.

irb(main):038:0> puts puts
most like
Programming language
=> nil

Of course, if you use puts variable (puts), you can output the character string stored in the variable earlier.

By the way, here documents can be output by expression expansion even when character strings and numbers are assigned to variables in advance.

irb(main):059:0> name = "Takeshi"
=> "Takeshi"
irb(main):060:0> age = 12
=> 12
irb(main):062:0> city = "Kanagawa"
=> "Kanagawa"
irb(main):063:0> text = <<EOF
irb(main):064:0"my name is#{name}is
irb(main):065:0"Age is#{age}
irb(main):066:0"I'm from#{city}
irb(main):067:0" EOF
=> "My name is Takeshi\n age is 12\I'm from Kanagawa\n"
irb(main):069:0> puts text
My name is Takeshi
Age is 12
I'm from Kanagawa

This time, I studied about here documents and output them.

Recommended Posts

[ruby] About here documents
About Ruby symbols
About ruby ​​form
About Ruby Hashes
About Ruby arrays
About Ruby inheritance
About ruby block
About Ruby Hashes
About Ruby Symbols
About Ruby variables
About Ruby methods
About Ruby Kernel Module
About Ruby error messages
About Ruby exception handling
About Ruby Hashes (continued)
About eval in Ruby
About Ruby if statement
About Ruby instance methods
[Ruby] About instance generation
About the [ruby] operator
Thinking about logic Ruby
Explanation about Ruby Range object
[Ruby on Rails] about has_secure_password
About regular expressions in Ruby
About Ruby hashes and symbols
Ruby About various iterative processes
About Ruby and object model
About Ruby classes and instances
Explanation about Ruby String object
About Ruby single quotes and double quotes
About Ruby product operator (&) and sum operator (|)
[Super Introduction] About Symbols in Ruby
About =
About object-oriented inheritance and about yield Ruby
[Ruby] Review about nesting of each
Explanation about Array object of Ruby
[Ruby on Rails] About bundler (for beginners)
[Ruby on Rails] About Active Record callbacks