Strings

 
   

Ruby Way
By Hal Fulton
Slots : 1.0
Table of Contents
 


String objects are instances of the String class, and have their own methods.

 

 "abc123".length  # 6 

They are not immutable by default, but you can make them immutable via the freeze method. Strings are not lists of characters, and accessing a single element returns the ASCII value for the byte, not the character.

 

 str = 'ABC' puts str[0]   # 65 puts ?A    # 65 puts str[0,1]  # "A" puts str[0].chr  # "A" 

The numeric approach facilitates languages having multi-byte characters, such as Japanese.

Iterating over a string will by default deliver one line at a time. You can also iterate over one byte at a time, but remember that you might need to convert bytes to characters.

 

 "abc".each_byte do |b| # convert to character before   print b.chr.upcase # using string method  end      # "ABC" 

There is no equivalent to Python's r"" raw string or the u"" Unicode string. Using double quotes has a different effect from using single quotes because they allow interpolation. Backticks are also different in Ruby, treating their contents as a shell command and evaluating them on the spot. Regular expressions likewise have special default quoting (forward slashes):

 

 'a do-nothing string'   # escape single quotes and backslashes "This is\ntwo lines."  # Notice - not like single quotes `ls -l`                 # Notice - not repr() /^(.*?)=(.*?)$/         # regex literal 

Ruby has special quoting constructs so you can specify other delimiters for these; refer to documentation of %q, %Q, %x, and %r.

Ruby allows for string interpolation in addition to the familiar % formatting.

 

 x = 5 puts "I have %s apples" % (x-2) puts "I have #{ x-2}  apples." 

Ruby's string interpolator, #{}, can be used inside double quote constructs, regexes, and shell strings. You can use "here-docs" in place of Python's triple quotes.

 

 heredoc = <<MARKER Now I can type "freely" Date: #{ Time.now} MARKER 

Here-docs also come in other forms supporting single- and shell-quoted strings, as well as indented here-docs.

 

 def whois(domain=nil)  print <<-`SHELL`  whois #{ domain||gets} @networksolutions.com  SHELL end 


   

 

 



The Ruby Way
The Ruby Way, Second Edition: Solutions and Techniques in Ruby Programming (2nd Edition)
ISBN: 0672328844
EAN: 2147483647
Year: 2000
Pages: 119
Authors: Hal Fulton

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net