I feel I should preemptively apologize because this seems like the type of question that's probably been asked before. I couldn't find an answer so I'm asking here.
I'm going through the RubyKoans and I'm at line:24 of about_strings.rb
There's a test:
def test_use_flexible_quoting_to_handle_really_hard_cases
a = %(flexible quotes can handle both ' and " characters)
b = %!flexible quotes can handle both ' and " characters!
c = %{flexible quotes can handle both ' and " characters}
assert_equal true, a == b
assert_equal true, a == c
end
So what exactly is the difference between a, b, and c. Why exactly do three ways of doing something exist? This seems illogical. I know Ruby is flexible but I don't think of it as illogical.
The basic difference between these two methods is Single quotes can not hold/print escape sequences directly, while double quotes can. i.e. Double quoted strings are used for String Interpolation in Ruby.
The difference The essential difference between the two literal forms of strings (single or double quotes) is that double quotes allow for escape sequences while single quotes do not! A string literal created by single quotes does not support string interpollation and does not escape sequences.
There's not three ways, there's... a lot of ways. Any non-alphanumeric character that follows % is a valid delimiter.
%[this is a valid string]
%~this is a valid string~
%+this is a valid string+
etc.
Note that brackets-and-friends are a little special, ruby is smart enough to allow you to use pairs of them - or even nest balanced pairs inside, a la
%[this is a [valid] string]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With