mirror of
https://github.com/jbranchaud/til
synced 2026-01-03 07:08:01 +00:00
Add Define Multiline Strings With Heredocs as a Ruby TIL
This commit is contained in:
@@ -10,7 +10,7 @@ pairing with smart people at Hashrocket.
|
||||
|
||||
For a steady stream of TILs, [sign up for my newsletter](https://crafty-builder-6996.ck.page/e169c61186).
|
||||
|
||||
_1411 TILs and counting..._
|
||||
_1412 TILs and counting..._
|
||||
|
||||
---
|
||||
|
||||
@@ -1116,6 +1116,7 @@ _1411 TILs and counting..._
|
||||
- [Defaulting To Frozen String Literals](ruby/defaulting-to-frozen-string-literals.md)
|
||||
- [Define A Custom RSpec Matcher](ruby/define-a-custom-rspec-matcher.md)
|
||||
- [Define A Method On A Struct](ruby/define-a-method-on-a-struct.md)
|
||||
- [Define Multiline Strings With Heredocs](ruby/define-multiline-strings-with-heredocs.md)
|
||||
- [Destructure The First Item From An Array](ruby/destructure-the-first-item-from-an-array.md)
|
||||
- [Destructuring Arrays In Blocks](ruby/destructuring-arrays-in-blocks.md)
|
||||
- [Disassemble Some Codes](ruby/disassemble-some-codes.md)
|
||||
|
||||
47
ruby/define-multiline-strings-with-heredocs.md
Normal file
47
ruby/define-multiline-strings-with-heredocs.md
Normal file
@@ -0,0 +1,47 @@
|
||||
# Define Multiline Strings With Heredocs
|
||||
|
||||
[A _heredoc_ (_here document_) is a special ruby
|
||||
syntax](https://ruby-doc.org/core-2.5.0/doc/syntax/literals_rdoc.html#label-Here+Documents)
|
||||
for defining formatted multiline strings. These are useful for any situation
|
||||
where you need to define a block of text where newlines and indentation are
|
||||
preserved -- e.g. output an error, help message, or some formatted SQL.
|
||||
|
||||
The standard syntax is defined with `<<` and some uppercase identifier (e.g.
|
||||
`TXT`, `DOC`, `SQL`, etc.) to open and close the multiline string.
|
||||
|
||||
```ruby
|
||||
def lookup_team(team_id)
|
||||
query = <<SQL
|
||||
select users.id from users
|
||||
join teams
|
||||
on teams.id = users.team_id
|
||||
where teams.id = #{team_id}
|
||||
order by created_at desc
|
||||
limit 10;
|
||||
SQL
|
||||
|
||||
team_member_ids = db.execute(query)
|
||||
end
|
||||
```
|
||||
|
||||
With the SQL formatted this way, it is easier to read and we can print/log out
|
||||
this nicely formatted version to make debugging easier.
|
||||
|
||||
Notice that the terminating `SQL` identifier is fully left justified. I find
|
||||
that visually off relative to the indentation of everything else, so I like to
|
||||
use the _indented_ heredoc syntax (`<<-`).
|
||||
|
||||
```ruby
|
||||
def lookup_team(team_id)
|
||||
query = <<-SQL
|
||||
select users.id from users
|
||||
join teams
|
||||
on teams.id = users.team_id
|
||||
where teams.id = #{team_id}
|
||||
order by created_at desc
|
||||
limit 10;
|
||||
SQL
|
||||
|
||||
team_member_ids = db.execute(query)
|
||||
end
|
||||
```
|
||||
Reference in New Issue
Block a user