Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Ruby

Thành Thạo Escape String Ruby: Xử Lý Quotes Và Ký Tự Đặc Biệt

Bài này nói về escaping characters trong Ruby. Ta học cách escape characters, cách nó work, và avoid escaping altogether cho some use cases. Nếu nghĩ bạn biết hết về \ , đọc hết và bị surprised...

Dive ngay vào character escaping trong strings.

Escaping Quotes

Khi dùng strings Ruby, đôi khi cần put quote dùng define string vào bên trong string. Khi đó, escape quote character với backslash \ symbol.

# Escape quotes in double quoted strings "Hello \"world\"!" => "Hello \"world\"!" # Escape quotes in single quoted strings 'Hello \'world\'!' => "Hello 'world'!"

Thấy Ruby default double quoted strings cho output và chỉ escape double quotes trong output.

Escape Sequences

Ngoài quotes, có nhiều symbols escape trong strings. Ví dụ, newline represented by \n. Gọi là "escape sequence".

"Hello\nworld" => "Hello\nworld"

Return same string tạo, nhưng \n highlighted, chỉ là escape sequence. Nếu print string này, literal \n không in, actual newline in thay thế.

puts "Hello\nworld" => Hello world

Điều này không work trong single quoted strings. Sequence \n interpreted as literal \n. Trong double quoted strings phải escape backslash symbol để same result.

'\n' => "\\n"

Ví dụ escape sequences khác work similarly: \t, \s và \b, represent tab, space, backspace.

Single Quotes vs And Double Quotes

Khác biệt single/double quoted strings Ruby là cách string definitions represent escape sequences.

  • Double quoted strings: viết escape sequences, Ruby output translated meaning. \n thành newline.
  • Single quoted strings: escape sequences bị escape, return literal definition. \n vẫn \n.

Cả 2 string types có use cases. Bạn likely dùng double quoted strings với escape sequences dùng translated meaning, newline/tab.

Single quotes useful avoid escaping escape sequences themselves. Useful demo usage hoặc avoid accidentally dùng escape sequences không intend.

puts "Line 1\nLine 2" => Line 1 Line 2 puts 'Using a \n we can indicate a newline.' => Using a \n we can indicate a newline.

Escaping Interpolation

Ruby support interpolation inside strings. Nhưng không all string definitions created equal. Interpolation chỉ work double quoted strings.

Code example dưới thấy interpolation work double quoted string, nhưng Ruby escape interpolation sequence single quoted string, render useless.

name = "world" "Hello #{name}" => "Hello world" 'Hello #{name}' => "Hello \#{name}"

Behavior này apply cho hầu hết string "magic". Double quotes support, single quotes không.

Percent Notation Cho String

Percent notation Ruby inspired by Perl, cho nhiều shorthands common type definitions.

Same behavior single/double quoted strings apply cho percent notation.

  • %() và %Q() behave same double quoted string.
  • %q() behave same single quoted string.

Vấn đề percent notation: cần escape parenthesis () thay quotes khi parenthesis không balanced.

Ruby allow dùng symbols khác cho percent notation: %[foo], %{foo}, %-foo-, %?foo?, etc. Hỗ trợ %"foo" và %'foo'.

Thấy Ruby escape string cho ta khi dùng percent notation.

%(Hello "world"!) => "Hello \"world\"" # With unbalanced parenthesis %(Hello world\)!) => "Hello world)!" # With balanced parenthesis %(Hello (world)!) => "Hello (world)!"

Lại same rules apply như normal single/double quoted strings. Escape sequences và interpolation escape mặc định single quoted strings.

name = "world" %(Hello\n "#{name}"!) => "Hello\n \"world\"!" %q(Hello\n "#{name}"!) => "Hello\\n \"\#{name}\"!" %Q(Hello\n "#{name}"!) => "Hello\n \"world\"!"

Escaping Characters Trong Regular Expressions

Escaping characters cũng work regular expressions. Trong regex nhiều characters represent hơn literal definition.

. wildcard any character, brackets [] represent range/selection, parentheses () match expression, etc. Dùng literal definitions escape với backslash.

/Hello \[world\]/ => /Hello \[world\]/ /\[world\]/ =~ "Hello [world]" => 6

Nếu không escape brackets, nó tìm any characters giữa brackets, tìm first match character l trong "Hello" position 3.

/[world]/ =~ "Hello [world]" => 2 # zero index

Tránh escape forward slash / dùng define regex, dùng percent notation khác.

%r{/world/} => /\/world\//

Dùng %r{} define regex không escape forward slash. Kết quả thấy Ruby escape forward slash cho ta.

Escaping Line Breaks

Trước escaped "newline" escape sequence \n trong string Ruby. Biết không escape line break trong Ruby itself?

Ví dụ, very long line method call break code style guide max line length.

ruby_method_with_many_arguments "Hello world", split: " ", join: "\n"

Có thể place arguments separate lines làm mỗi line shorter. Work miễn previous line end với comma ,, operators như plus +, hoặc part of method call wrapped parentheses ().

ruby_method_with_many_arguments "Hello world", split: " ", join: "\n" ruby_method_with_many_arguments( "Hello world", split: " ", join: "\n" )

Nếu muốn align all arguments same indentation level không wrap parentheses (), dùng backslash \ escape line break.

ruby_method_with_many_arguments \ my_string, split: " ", join: "\n"

Điều ta làm không real tell Ruby escape newline, mà statement continue next line.

Escaping Line Breaks Trong String Definitions

Escaping line ending cũng work string definitions. Thường multi-line string dùng plus + combine strings 2 lines.

"foo" + "bar" => "foobar"

Tạo 2 strings 2 lines combine as one. Thực ra tạo 3 string objects.

Thay vì plus symbol, escape line break với backslash.

"foo" \ "bar" => "foobar"

Result same, hay không?

Ví dụ đầu combine 2 new strings, ví dụ 2 Ruby thấy backslash \ as continuation string definition, chỉ tạo 1 string based on 2 lines. Better cho app memory usage.

Kết Luận

Escaping characters Ruby, và nhiều languages khác, quite confusing. Đột nhiên certain character combos khác meaning trong double quoted string vs single quoted string.

Hy vọng little guide giúp hiểu properly escape characters và sequences Ruby. Khác biệt double/single quoted string là key.

String "magic" escape sequences và interpolation chỉ really work double quoted strings, không single quoted strings.

Còn other ways escape code Ruby. Percent notation giúp avoid escape certain characters all the time, strings và regex.

Nhưng backslash cũng very useful viết multi-line strings và continue line Ruby code next line. Dùng nhiều keep code clean readable.

Liên hệ @AppSignal nếu muốn biết thêm, hoặc specific question escaping characters Ruby.

Fun side-note: bài này viết Markdown, tôi dùng backslash khá nhiều. Giống Ruby, Markdown allow escaping certain characters. Thường Markdown không wrap backslash trong code block vì escape code block itself. Thay vào đó escape space.

`\` # Doesn't work `\ ` # Works :)