使用Ruby来处理文本的教程

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

与 Perl 和 Python 类似,Ruby 拥有出色的功能,是一种强大的文本处理语言。本文简单介绍了 Ruby 的文本数据处理功能,以及如何使用 Ruby 语言有效处理不同格式的文本数据,无论是 CSV 数据还是 XML 数据。
Ruby 字符串
常用缩略词

    CSV:逗号分隔值     REXML:Ruby Electric XML     XML:可扩展标记语言

Ruby 中的 String 是容纳、比较和操作文本数据的一种强大方法。在 Ruby 中,String 是一个类,可以通过调用 String::new 或向它分配一个字面值将它实例化。

向 Strings 赋值时,可以使用单引号(')或双引号(")来包围值。单引号和双引号在为 Strings 赋值时有几个差别。双引号支持转义序列使用一个前置反斜杠()并支持在字符串中使用 #{} 操作符计算表达式。而单引号引用的字符串则是简单直接的文字。

清单 1 是一个示例。
清单 1. 处理 Ruby 字符串:定义字符串

message = 'Heal the World…'

puts message

message1 = "Take home Rs #{100*3/2} "

puts message1

Output :

# ./string1.rb

# Heal the World…

# Take home Rs 150

这里,第一个字符串使用一对单引号定义,第二个字符串使用一对双引号定义。在第二个字符串中,#{} 中的表达式在显示前计算。

另一种有用的字符串定义方法通常用于多行字符串定义。

从现在开始,我将使用交互式 Ruby 控制台 irb>> 进行说明。您的 Ruby 安装也应该安装该控制台。如果没有安装,建议您获取 irb Ruby gem 并安装它。Ruby 控制台是学习 Ruby 及其模块的一个非常有用的工具。安装之后,可以使用 irb>> 命令运行它。
清单 2. 处理 Ruby 字符串:定义多个字符串

irb>> str = >>EOF

irb>> "hello world

irb>> "how do you feel?

irb>> "how r u ?

irb>> EOF

"hello, worldnhow do you feel?nhow r u?n"

irb>> puts str

hello, world
how do you feel?
how r u?

在 清单 2 中,>>EOF 和 EOF 中的所有内容都视为字符串的一部分,包括 n(换行)字符。

Ruby String 类有一组强大的方法用于操作和处理存储在它们之中的数据。清单 3、4 和 5 中的示例展示了部分方法。
清单 3. 处理 Ruby 字符串:连接字符串

irb>> str = "The world for a horse" # String initialized with a value

The world for a horse

irb>> str*2      # Multiplying with an integer returns a 
           # new string containing that many times
           # of the old string.

The world for a horseThe world for a horse

irb>> str + " Who said it ? "  # Concatenation of strings using the '+' operator

The world for a horse Who said it ?

irb>> str<<" is it? " # Concatenation using the '<<' operator

The world for a horse is it?