Is there any difference between flexible quotes in a ruby?

I feel like I have to proactively apologize because it seems like a question that was probably asked before. I could not find the answer, so I ask here.

I go through RubyKoans and I'm on line: 24 of about_strings.rb There 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 is the difference between a, b and c. Why exactly three ways to do something exist? This seems counterintuitive. I know that Ruby is flexible, but I do not consider it illogical.

+4
source share
4 answers

Look at other languages ​​and you will see the same.

, , % . "

+5

, ... . -- , %, .

%[this is a valid string]
%~this is a valid string~
%+this is a valid string+

.

, , , - , a la

%[this is a [valid] string]
+7

%{..}, %!..! .. , %Q{}, , . , %{..}, %!..! %q{..}.

>> x = 5
=> 5
>> %q[#{x}] # interpolation not happened
=> "\#{x}"
>> %[#{x}] # interpolation happened
=> "5"
>> %Q[#{x}] # interpolation happened
=> "5"
>> 

% Notation

Perl- : % ( ) , :

%{78% of statistics are "made up" on the spot}
# => "78% of statistics are \"made up\" on the spot"

- , %[including these], %?or these?, %~or even these things~. , - " ' unescaped, , , , , , . , %(parentheses), %[square brackets], %{curly brackets} %<pointy brackets> , , :

%(string (syntax) is pretty flexible)
# => "string (syntax) is pretty flexible"
0

In Ruby, you have the syntax "flexible quotation marks", which is as follows: %[any non-word, non-whitespace character]String[opening character or closing bracket]. Thus, you can use almost any character without a word and without spaces as a separator.

0
source

Source: https://habr.com/ru/post/1529491/


All Articles