Is there an easy way to do multiline indented strings in Ruby? -
this question has answer here:
say wanted have large block of pretty printed html code strait inline ruby code. cleanest way without losing formatting in string or having remember sort of gsub regex.
encoding in 1 line easy hard read:
1.times # note spaces have been changed _ easy see here. doc = "\n<html>\n__<head>\n____<title>\n______title\n____</title>\n__</head>\n__<body>\n____body\n__</body>\n</html>\n" ans = "your document: %s" % [doc] puts ans end
multiline text in ruby easier read string can't indented rest of code:
1.times doc = " <html> <head> <title> title </title> </head> <body> body </body> </html> " ans = "your document: %s" % [doc] puts ans end
for example following indented code, string has 4 spaces in front of every line:
1.times doc = <<-eom <html> <head> <title> title </title> </head> <body> body </body> </html> eom ans = "your document: %s" % [doc] puts ans end
most people go heredoc code above, , regex replace on result take out whitespace @ beginning of each line. way don't have go through trouble of regexing each time.
string = %q{this indented , has newlines}
here blog examples of %q{}
, %q{}
, others.
as far having easy remember, think 'q' `quotation marks'.
sidenote: technically don't need 'q' while doing quotation.
string = %{this indented , has newlines , handles interpolation 1 + 1 = #{1+1} }
however, best practice , more readable use %q{}
.
Comments
Post a Comment