Skip to content

Commit b766f20

Browse files
committed
Add Define Multiline Strings With Heredocs as a Ruby TIL
1 parent 505220d commit b766f20

File tree

2 files changed

+49
-1
lines changed

2 files changed

+49
-1
lines changed

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ pairing with smart people at Hashrocket.
1010

1111
For a steady stream of TILs, [sign up for my newsletter](https://crafty-builder-6996.ck.page/e169c61186).
1212

13-
_1411 TILs and counting..._
13+
_1412 TILs and counting..._
1414

1515
---
1616

@@ -1116,6 +1116,7 @@ _1411 TILs and counting..._
11161116
- [Defaulting To Frozen String Literals](ruby/defaulting-to-frozen-string-literals.md)
11171117
- [Define A Custom RSpec Matcher](ruby/define-a-custom-rspec-matcher.md)
11181118
- [Define A Method On A Struct](ruby/define-a-method-on-a-struct.md)
1119+
- [Define Multiline Strings With Heredocs](ruby/define-multiline-strings-with-heredocs.md)
11191120
- [Destructure The First Item From An Array](ruby/destructure-the-first-item-from-an-array.md)
11201121
- [Destructuring Arrays In Blocks](ruby/destructuring-arrays-in-blocks.md)
11211122
- [Disassemble Some Codes](ruby/disassemble-some-codes.md)
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
# Define Multiline Strings With Heredocs
2+
3+
[A _heredoc_ (_here document_) is a special ruby
4+
syntax](https://ruby-doc.org/core-2.5.0/doc/syntax/literals_rdoc.html#label-Here+Documents)
5+
for defining formatted multiline strings. These are useful for any situation
6+
where you need to define a block of text where newlines and indentation are
7+
preserved -- e.g. output an error, help message, or some formatted SQL.
8+
9+
The standard syntax is defined with `<<` and some uppercase identifier (e.g.
10+
`TXT`, `DOC`, `SQL`, etc.) to open and close the multiline string.
11+
12+
```ruby
13+
def lookup_team(team_id)
14+
query = <<SQL
15+
select users.id from users
16+
join teams
17+
on teams.id = users.team_id
18+
where teams.id = #{team_id}
19+
order by created_at desc
20+
limit 10;
21+
SQL
22+
23+
team_member_ids = db.execute(query)
24+
end
25+
```
26+
27+
With the SQL formatted this way, it is easier to read and we can print/log out
28+
this nicely formatted version to make debugging easier.
29+
30+
Notice that the terminating `SQL` identifier is fully left justified. I find
31+
that visually off relative to the indentation of everything else, so I like to
32+
use the _indented_ heredoc syntax (`<<-`).
33+
34+
```ruby
35+
def lookup_team(team_id)
36+
query = <<-SQL
37+
select users.id from users
38+
join teams
39+
on teams.id = users.team_id
40+
where teams.id = #{team_id}
41+
order by created_at desc
42+
limit 10;
43+
SQL
44+
45+
team_member_ids = db.execute(query)
46+
end
47+
```

0 commit comments

Comments
 (0)