Skip to content

Commit 38f3258

Browse files
committed
Add Single And Double Quoted String Notation as a ruby til
1 parent 421ed7b commit 38f3258

File tree

2 files changed

+40
-1
lines changed

2 files changed

+40
-1
lines changed

README.md

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

1010
For a steady stream of TILs, [sign up for my newsletter](https://tinyletter.com/jbranchaud).
1111

12-
_865 TILs and counting..._
12+
_866 TILs and counting..._
1313

1414
---
1515

@@ -706,6 +706,7 @@ _865 TILs and counting..._
706706
- [Set RVM Default Ruby](ruby/set-rvm-default-ruby.md)
707707
- [Show Public Methods With Pry](ruby/show-public-methods-with-pry.md)
708708
- [Silence The Output Of A Ruby Statement In Pry](ruby/silence-the-output-of-a-ruby-statement-in-pry.md)
709+
- [Single And Double Quoted String Notation](ruby/single-and-double-quoted-string-notation.md)
709710
- [Squeeze Out The Extra Space](ruby/squeeze-out-the-extra-space.md)
710711
- [String Interpolation With Instance Variables](ruby/string-interpolation-with-instance-variables.md)
711712
- [Summing Collections](ruby/summing-collections.md)
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
# Single And Double Quoted String Notation
2+
3+
If you are building a string that involves interpolation and literal double
4+
quotes, then you'll have to do some escaping. Here is an example:
5+
6+
```ruby
7+
> feet, inches = [6, 4]
8+
> puts "I am #{feet}'#{inches}\" tall"
9+
I am 6'4" tall
10+
```
11+
12+
Having to escape a single instance of a double quote isn't so bad. If you find
13+
yourself having to do it a bunch, Ruby has something for you. It is a string
14+
syntax feature called [Percent Notation](percent-notation.md).
15+
16+
You can use percent notation to define double-quoted strings using `Q`:
17+
18+
```ruby
19+
> puts %Q[I am #{feet}'#{inches}" tall]
20+
I am 6'4" tall
21+
```
22+
23+
No need to escape the double quote here.
24+
25+
There is a single-quoted version as well using `q`:
26+
27+
```ruby
28+
> puts %q[I am #{feet}'#{inches}\" tall]
29+
I am #{feet}'#{inches}\" tall
30+
```
31+
32+
This is notably less useful than `%Q`. For that reason, `%Q` makes sense as a
33+
default and it makes up the percent notations unmodified behavior:
34+
35+
```ruby
36+
> puts %[I am #{feet}'#{inches}" tall]
37+
I am 6'4" tall
38+
```

0 commit comments

Comments
 (0)