Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a difference between flexible quotes in ruby?

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.

like image 551
Joe Susnick Avatar asked Feb 28 '14 22:02

Joe Susnick


People also ask

What is the main difference between single quotes and double quotes Ruby?

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.

What's the difference between single quotes or double quotes when using string interpolation?

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.


Video Answer


1 Answers

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]
like image 160
roippi Avatar answered Oct 03 '22 22:10

roippi