• linkedu视频
  • 平面设计
  • 电脑入门
  • 操作系统
  • 办公应用
  • 电脑硬件
  • 动画设计
  • 3D设计
  • 网页设计
  • CAD设计
  • 影音处理
  • 数据库
  • 程序设计
  • 认证考试
  • 信息管理
  • 信息安全
菜单
linkedu.com
  • 网页制作
  • 数据库
  • 程序设计
  • 操作系统
  • CMS教程
  • 游戏攻略
  • 脚本语言
  • 平面设计
  • 软件教程
  • 网络安全
  • 电脑知识
  • 服务器
  • 视频教程
  • vbs
  • DOS/BAT
  • hta/htc
  • python
  • perl
  • VBA
  • ColdFusion
  • ruby
  • PowerShell
  • Lua
  • Golang
  • linux shell
您的位置:首页 > 脚本语言 >ruby > 使用Ruby来处理文本的教程

使用Ruby来处理文本的教程

作者:goldensun 字体:[增加 减小] 来源:互联网

goldensun 通过本文主要向大家介绍了max and ruby文本,ruby教程,ruby on rails教程,ruby安装教程,ruby语言入门教程等相关知识,希望对您有所帮助,也希望大家支持linkedu.com www.linkedu.com

与 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

</div>

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

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

从现在开始,我将使用交互式 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, world\nhow do you feel?\nhow r u?\n"

irb>> puts str

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

</div>

在 清单 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?

</div>

提取子字符串并操作字符串的多个部分
清单 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"

</div>

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

</div>

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

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

处理 CSV 文件

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

Ruby 有一个强大的库,可以用于处理这些文件。csv 是负责处理 CSV 文件的 Ruby 模块,它拥有创建、读取和解析 CSV 文件的方法。

清单 6 展示了如何创建一个 CSV 文件并使用 Ruby csv 模块来解析文件。
清单 6. 处理 CSV 文件:创建并解析一个 CSV 文件

require 'csv'

writer = CSV.open('mycsvfile.csv','w')

begin

 print "Enter Contact Name: "

 name = STDIN.gets.chomp

 print "Enter Contact No: "

 num = STDIN.gets.chomp

 s = name+" "+num

 row1 = s.split

 writer << row1

 print "Do you want to add more ? (y/n): "

 ans = STDIN.gets.chomp

end while ans != "n"

writer.close

file = File.new('mycsvfile.csv')

lines = file.readlines

parsed = CSV.parse(lines.to_s)

p parsed

puts ""

puts "Details of Contacts stored are as follows..."

puts ""

puts "-------------------------------"

puts "Contact Name | Contact No"

puts "-------------------------------"

puts ""

CSV.open('mycsvfile.csv','r') do |row|

 puts row[0] + " | " + row[1] 

 puts ""
end

</div>

清单 7 显示了输出:
清单 7. 处理 CSV 文件:创建并解析一个 CSV 文件输出

Enter Contact Name: Santhosh

Enter Contact No: 989898

Do you want to add more ? (y/n): y

Enter Contact Name: Sandy

Enter Contact No: 98988

Do you want to add more ? (y/n): n

Details of Contacts stored are as follows...

---------------------------------
Contact Name | Contact No
---------------------------------

Santhosh | 989898

Sandy | 98988

</div>

让我们快速检查一下这个示例。

首先,包含 csv 模块(require 'csv')。

要创建一个新的 CSV 文件 mycsvfile.csv,使用 CSV.open() 调用打开它。这返回一个写入器(writer)对象。

这个示例创建了一个 CSV 文件,该文件包含一个简单的联系人列表,存储联系人姓名及其电话号码。在循环中,用户被要求输入联系人姓名和电话号码。姓名和电话号码被连接为一个字符串,然后分割为含两个字符串的数组。这个数组传递到写入器对象以便写入 CSV 文件。这样,一对 CSV 值就存储为文件中的一行。

循环结束后,任务也就完成了。现在关闭写入器,文件中的数据得以保存。

下一步是解

您可能想查找下面的文章:

  • 使用Ruby来处理文本的教程

相关文章

  • Ruby对比Python的优势和劣势
  • openSUSE下的Ruby安装openssl出错解决方法
  • Ruby和Ruby on Rails中解析JSON格式数据的实例教程
  • 进一步深入Ruby中的类与对象概念
  • 详解Ruby中的代码块及其参数传递
  • Ruby中编写类与模块的风格指南
  • 使用Ruby编写脚本进行系统管理的教程
  • Ruby中的循环语句的用法教程
  • Ruby程序中正则表达式的基本使用教程
  • Ruby中的Proc类及Proc的类方法Proc.new的使用解析

文章分类

  • vbs
  • DOS/BAT
  • hta/htc
  • python
  • perl
  • VBA
  • ColdFusion
  • ruby
  • PowerShell
  • Lua
  • Golang
  • linux shell

最近更新的内容

    • Ruby使用设计模式中的代理模式与装饰模式的代码实例
    • 使用Ruby来编写访问Twitter的命令行应用程序的教程
    • ruby 标准类型总结
    • Ruby中使用连续体Continuation实现生成器
    • Ruby 字符串处理
    • Ruby On Rails中如何避免N+1问题
    • 一个简单的Ruby可逆加密解密类
    • 使用Ruby编写发送邮件的程序的简单教程
    • ruby 迭代器使用方法
    • rails 连接mysql的问题解决

关于我们 - 联系我们 - 免责声明 - 网站地图

©2020-2025 All Rights Reserved. linkedu.com 版权所有