使用Ruby来处理文本的教程

2019-09-25 09:44:57丽君

提取子字符串并操作字符串的多个部分
清单 4. 处理 Ruby 字符串:提取并操作

irb>> str[0] # The '[]' operator can be used to extract substrings, just 
      # like accessing entries in an array.
      # The index starts from 0.
84 # A single index returns the ascii value
      # of the character at that position

irb>> str[0,5] # a range can be specified as a pair. The first is the starting 
      # index , second is the length of the substring from the
      # starting index.

The w

irb>> str[16,5]="Ferrari" # The same '[]' operator can be used
         # to replace substrings in a string
         # by using the assignment like '[]='
irb>>str

The world for a Ferrari

Irb>> str[10..22] # The range can also be specified using [x1..x2] 

for a Ferrari

irb>> str[" Ferrari"]=" horse" # A substring can be specified to be replaced by a new
        # string. Ruby strings are intelligent enough to adjust the
        # size of the string to make up for the replacement string.

irb>> s

The world for a horse

irb>> s.split  # Split, splits the string based on the given delimiter
        # default is a whitespace, returning an array of strings.

["The", "world", "for", "a", "horse"]

irb>> s.each(' ') { |str| p str.chomp(' ') }

        # each , is a way of block processing the
   # string splitting it on a record separator
   # Here, I use chomp() to cut off the trailing space

"The"
"world"
"for"
"a"
"horse"

Ruby String 类还可以使用许多其他实用方法,这些方法可以更改大小写、获取字符串长度、删除记录分隔符、扫描字符串、加密、解密等。另一个有用的方法是 freeze,该方法可以使字符串变得不可修改。对 String str 调用该方法(str.freeze)之后,str 将不能被修改。

Ruby 还有一些称为 “析构器(destructor)” 的方法。以感叹号(!)结尾的方法将永久修改字符串。常规方法(结尾没有感叹号)修改并返回调用它们的字符串的副本。而带有感叹号的方法直接修改调用它们的字符串。
清单 5. 处理 Ruby 字符串:永久修改字符串

irb>> str = "hello, world"

hello, world

irb>> str.upcase

HELLO, WORLD

irb>>str   # str, remains as is.

Hello, world

irb>> str.upcase!  # here, str gets modified by the '!' at the end of 
        # upcase.
HELLO, WORLD

irb>> str

HELLO, WORLD

在 清单 5 中,str 中的字符串由 upcase! 方法修改,但 upcase 方法只返回大小写修改后的字符串副本。这些 ! 方法有时很有用。

Ruby Strings 的功能非常强大。数据被捕获进 Strings 中后,您就能够任意使用多种方法轻松有效地处理这些数据。

处理 CSV 文件

CSV 文件是表示表格式的数据的一种很常见的方法,表格式通常用作从电子表格导出的数据(比如带有详细信息的联系人列表)的格式。