File.open("db/quotes/#{id}.json", "w") do |f|
f.write <<TEMPLATE
{
"submitter": "{hash["submitter"]}",
"quote": "{hash["quote"]}",
"attribution": "{hash["attribution"]}"
}
TEMPLATE
end
I understand what this method is doing. I read this code snippet out of a book. It is trying to write to a json to a file with whatever name #{id}.json is. I have never seen it before. Is "<<" an operator? What is "TEMPLATE"? Btw, this it out of the book rebuilding ruby on rails. In the section of rebuilding the Model layer is where i found the code snippet. It could have something to do with the Gem "erubis".
f.write
expects a string as an argument and writes that string to the file f
.
<<TEMPLATE
starts a string that ends at the next occurrence of TEMPLATE
. This kind of strings are called heredocs .
It's here-document
syntax for string. It's a way to represent a string spanning multiple lines and the indentation will be preserved.
str = <<EOF
this will be the content
of your string
EOF
You can choose whatever word you want where I put EOF.
The other answers point you in the right direction of heredocs .
Technically this is syntax error with the string never terminating.
begin
str = <<EOS
This is my string
EOS
end
Because the EOS
at the beginning of the line. The below example works:
begin
str = <<EOS
This is my string
EOS
end
To have correctly indented code you would do the following:
begin
str = <<-EOS
This is my string
EOS
end
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.