Ruby/String/Escape Characters

Материал из Wiki.crossplatform.ru

(Различия между версиями)
Перейти к: навигация, поиск
м (1 версия)
 

Текущая версия на 17:56, 13 сентября 2010

Содержание

Check the length of a string which has the control character inside

french_string = "il \xc3\xa9tait une fois"   # => "il \303\251tait une fois"
french_string.length                         # => 18



Construct a string from hex value

"\x10\x11\xfe\xff"                 # => "\020\021\376\377"
"\x48\145\x6c\x6c\157\x0a"         # => "Hello\n"



Escape a single quote

puts "it may look like this string contains a newline\nbut it doesn\"t"



Escape backslash

puts "Here is a backslash: \\ "



Escape Characters list

Backslash notation  Hexadecimal character   Description
\a                  0x07                    Bell or alert
\b                  0x08                    Backspace
\cx                                         Control-x
\C-x                                        Control-x
\e                  0x1b                    Escape
\f                  0x0c                    Formfeed
\M-\C-x                                     Meta-Control-x
\n                  0x0a                    Newline
\nnn                                        Octal notation, where n is in the range 0-7
\r                  0x0d                    Carriage return
\s                  0x20                    Space
\t                  0x09                    Tab
\v                  0x0b                    Vertical tab
\x                                          Character x
\xnn                                        Hexadecimal notation, where n is in the range 0-9, a-f, or A-F



Escape sequence and hex number

"\a" == "\x07"  # => true  #ASCII 0x07 = BEL (Sound system bell)
"\b" == "\x08"  # => true  #ASCII 0x08 = BS (Backspace)
"\e" == "\x1b"  # => true  #ASCII 0x1B = ESC (Escape)
"\f" == "\x0c"  # => true  #ASCII 0x0C = FF (Form feed)
"\n" == "\x0a"  # => true  #ASCII 0x0A = LF (Newline/line feed)
"\r" == "\x0d"  # => true  #ASCII 0x0D = CR (Carriage return)
"\t" == "\x09"  # => true  #ASCII 0x09 = HT (Tab/horizontal tab)
"\v" == "\x0b"  # => true  #ASCII 0x0B = VT (Vertical tab)



Put a string with control character

puts "This string\ncontains a newline"



Representing Unprintable Characters

octal = "\000\001\010\020"
octal.each_byte { |x| puts x }



String operation on escape char

"\\".size                          # => 1
"\\" == "\x5c"                     # => true
"\\n"[0] == ?\\                    # => true
"\\n"[1] == ?n                     # => true
"\\n" =~ /\n/                      # => nil



Tab key in double quotation

puts "foo\tbar"
# foo     bar



tab key in %q{}

puts %q{foo\tbar}
# foo\tbar



Tab key in single quotation mark

puts "foo\tbar"
# foo\tbar



Use Tab key in {}

puts %{foo\tbar}
# foo     bar



use tab key in %Q{}

puts %Q{foo\tbar}
# foo     bar