Ray's playground

 

Recipe 1.5. Representing Unprintable Characters

  Ruby gives you a number of escaping mechanisms to refer to unprintable characters. By using one of these mechanisms within a double-quoted string, you can put any binary character into the string.

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

# 0
# 1
# 8
# 16
  This makes it possible to represent UTF-8 characters even when you can't type them or display them in your terminal. Try running this program, and then opening the generated file smiley.html in your web browser:

1open('smiley.html''wb') do |f|
2  f << '<meta http-equiv="Content-Type" Content="text/html;charset=UTF-8">'
3  f << "\xe2\x98\xBA"
4end

 

  Ruby also provides special shortcuts for representing keyboard sequences like Control-C. "\C-_x_" represents the sequence you get by holding down the control key and hitting the x key, and "\M-_x_" represents the sequence you get by holding down the Alt (or Meta) key and hitting the x key:

  Special characters are only interpreted in strings delimited by double quotes, or strings created with %{} or %Q{}. They are not interpreted in strings delimited by single quotes, or strings created with %q{}. You can take advantage of this feature when you need to display special characters to the end-user, or create a string containing a lot of backslashes.

posted on 2009-11-03 22:40  Ray Z  阅读(173)  评论(0编辑  收藏  举报

导航