diff --git a/README.md b/README.md index 8cd5842..a7e93af 100644 --- a/README.md +++ b/README.md @@ -9,7 +9,7 @@ and pairing with smart people at Hashrocket. For a steady stream of TILs, [sign up for my newsletter](https://tinyletter.com/jbranchaud). -_865 TILs and counting..._ +_866 TILs and counting..._ --- @@ -706,6 +706,7 @@ _865 TILs and counting..._ - [Set RVM Default Ruby](ruby/set-rvm-default-ruby.md) - [Show Public Methods With Pry](ruby/show-public-methods-with-pry.md) - [Silence The Output Of A Ruby Statement In Pry](ruby/silence-the-output-of-a-ruby-statement-in-pry.md) +- [Single And Double Quoted String Notation](ruby/single-and-double-quoted-string-notation.md) - [Squeeze Out The Extra Space](ruby/squeeze-out-the-extra-space.md) - [String Interpolation With Instance Variables](ruby/string-interpolation-with-instance-variables.md) - [Summing Collections](ruby/summing-collections.md) diff --git a/ruby/single-and-double-quoted-string-notation.md b/ruby/single-and-double-quoted-string-notation.md new file mode 100644 index 0000000..d1947b7 --- /dev/null +++ b/ruby/single-and-double-quoted-string-notation.md @@ -0,0 +1,38 @@ +# Single And Double Quoted String Notation + +If you are building a string that involves interpolation and literal double +quotes, then you'll have to do some escaping. Here is an example: + +```ruby +> feet, inches = [6, 4] +> puts "I am #{feet}'#{inches}\" tall" +I am 6'4" tall +``` + +Having to escape a single instance of a double quote isn't so bad. If you find +yourself having to do it a bunch, Ruby has something for you. It is a string +syntax feature called [Percent Notation](percent-notation.md). + +You can use percent notation to define double-quoted strings using `Q`: + +```ruby +> puts %Q[I am #{feet}'#{inches}" tall] +I am 6'4" tall +``` + +No need to escape the double quote here. + +There is a single-quoted version as well using `q`: + +```ruby +> puts %q[I am #{feet}'#{inches}\" tall] +I am #{feet}'#{inches}\" tall +``` + +This is notably less useful than `%Q`. For that reason, `%Q` makes sense as a +default and it makes up the percent notations unmodified behavior: + +```ruby +> puts %[I am #{feet}'#{inches}" tall] +I am 6'4" tall +```