开发基础Ruby应用程序
立即解锁
发布时间: 2025-08-20 01:30:30 阅读量: 2 订阅数: 3 


Ruby编程入门与实践指南
### 开发基础 Ruby 应用程序
在学习编程的过程中,我们已经了解了 Ruby 语言的基础知识。现在,让我们进入实际软件开发的世界,开发一个完整的基础 Ruby 应用程序,并逐步扩展其功能。
#### 1. 处理源代码文件
在之前的学习中,我们主要使用 irb 即时 Ruby 提示符来学习语言。但对于需要重复使用的代码,将源代码存储在文件中是很有必要的。不同操作系统创建和操作源代码文件的方式不同:
- **Windows**:安装 Ruby 时,“开始”菜单的 Ruby 程序组中有 SciTE 和 FreeRIDE 两个文本编辑器。SciTE 是通用的源代码编辑工具,FreeRIDE 是用 Ruby 编写的特定于 Ruby 的编辑器。它俩都能通过“文件”菜单保存源代码到硬盘,FreeRIDE 还能将多个文件组织成一个项目。
- **Mac OS X**:有多种文本编辑器,如 TextMate(约 $50)受 Ruby 社区推崇,Xcode 是 OS X 开发工具中的选择但使用较复杂且可能较慢。免费的 TextEdit 默认不是纯文本编辑器,需在“格式”菜单中选择“转换为纯文本”才能用于编辑 Ruby 代码。
- **Linux**:不同发行版有不同的文本编辑器,如 vi、Emacs、pico、nano 等,图形界面下还有 Kate 和 gedit。也可下载安装 FreeRIDE,它能直接运行代码并对代码进行语法高亮。
#### 2. 创建测试文件
开发 Ruby 应用的第一步是熟悉文本编辑器。以下是不同平台的指导:
- **Windows**:使用 SciTE 或 FreeRIDE,打开编辑器后即可开始输入 Ruby 代码,用“文件”菜单保存。
- **Mac OS X**:使用 TextEdit,转换为纯文本模式后输入代码,通过“文件”➤“保存”保存到指定位置,建议在主文件夹下创建 ruby 文件夹保存代码。
- **Linux**:选择合适的编辑器,如 FreeRIDE,也可在主目录下创建 ruby 文件夹保存代码。
#### 3. 测试源代码文件
在能编辑和保存文本文件的环境中,输入以下代码:
```ruby
x = 2
print "This application is running okay if 2 + 2 = #{x + x}"
```
将代码保存为 a.rb 文件,建议创建一个容易找到的 ruby 文件夹存放。
#### 4. 运行源代码
创建好 a.rb 文件后,需让 Ruby 执行它,不同操作系统的执行方式不同:
- **Windows**:
- 使用 SciTE 或 FreeRIDE,按 F5 键或通过菜单(SciTE 的“工具”➤“运行”,FreeRIDE 的“运行”➤“运行”)运行,但要先保存代码。
- 从命令提示符运行,打开命令提示符,使用 cd 命令导航到包含 a.rb 的文件夹,然后输入 ruby a.rb。也可创建 Ruby 可执行文件的快捷方式,将源代码文件拖到上面运行。
- **Mac OS X**:
1. 启动终端(位于“应用程序”/“实用工具”)。
2. 使用 cd 命令导航到存放 a.rb 的文件夹,如 cd ~/ruby。
3. 输入 ruby a.rb 并按 Enter 执行。若出现错误,需确认文件保存位置。
- **Linux 和其他 Unix 系统**:
1. 启动终端模拟器,获得 Linux 命令提示符。
2. 使用 cd 命令导航到存放 a.rb 的文件夹,如 cd ~/ruby。
3. 输入 ruby a.rb 并按 Enter 执行。
#### 5. 我们的应用:文本分析器
我们要开发的应用是一个文本分析器,它能读取单独文件中的文本,分析各种模式和统计信息并输出结果。文本处理程序在系统管理和应用开发中很重要,Ruby 适合进行文本和文档分析。
##### 5.1 所需基本功能
文本分析器将提供以下基本统计信息:
|统计信息|说明|
| ---- | ---- |
|字符计数|文件中的字符总数|
|字符计数(不包括空格)|去除空格后的字符总数|
|行数|文件中的行数|
|单词计数|文件中的单词总数|
|句子计数|文件中的句子总数|
|段落计数|文件中的段落总数|
|平均每句单词数|总单词数除以总句子数|
|平均每段句子数|总句子数除以总段落数|
##### 5.2 构建基本应用
开发新程序时,可按以下步骤进行:
```mermaid
graph LR
A[加载要分析的文本文件] --> B[逐行加载文件并统计行数]
B --> C[将文本放入字符串并计算字符数]
C --> D[去除空格并计算字符数(不包括空格)]
D --> E[分割空格计算单词数]
E --> F[按句号分割计算句子数]
F --> G[按双换行符分割计算段落数]
G --> H[计算平均值]
```
创建一个新的空白 Ruby 源文件,保存为 analyzer.rb。
##### 5.3 获取测试文本
可从 http://www.rubyinside.com/book/oliver.txt 或 http://www.dickens-literature.com/Oliver_Twist/0.html 复制《雾都孤儿》第一章的文本到本地文件 text.txt,保存到与 a.rb 相同的文件夹。
##### 5.4 加载文本文件并统计行数
使用以下代码加载文件并统计行数:
```ruby
line_count = 0
File.open("text.txt").each { |line| line_count += 1 }
puts line_count
```
为了获取文件内容,可修改代码:
```ruby
text=''
line_count = 0
File.open("text.txt").each do |line|
line_count += 1
text << line
end
puts "#{line_count} lines"
```
也可使用更简单的方法:
```ruby
lines = File.readlines("text.txt")
line_count = lines.size
text = lines.join
puts "#{line_count} lines"
```
##### 5.5 统计字符数
在 analyzer.rb 中添加以下代码统计字符数:
```ruby
total_characters = text.length
puts "#{total_characters} characters"
```
统计不包括空格的字符数:
```ruby
total_characters_nospaces = text.gsub(/\s+/, '').length
puts "#{total_characters_nospaces} characters excluding spaces"
```
##### 5.6 统计单词数
有两种方法统计单词数:
```ruby
# 使用 scan 方法
puts "this is a test".scan(/\w+/).length
# 使用 split 方法
puts "this is a test".split.length
```
在 analyzer.rb 中添加以下代码统计单词数:
```ruby
word_count = text.split.length
puts "#{word_count} words"
```
##### 5.7 统计句子和段落数
在 analyzer.rb 中添加以下代码统计句子和段落数:
```ruby
paragraph_count = text.split(/\n\n/).length
puts "#{paragraph_count} paragraphs"
sentence_count = text.split(/\.|\?|!/).length
puts "#{sentence_count} sentences"
```
##### 5.8 计算平均值
在 analyzer.rb 中添加以下代码计算平均值:
```ruby
puts "#{sentence_count / paragraph_count} sentences per paragraph (average)"
puts "#{word_count / sentence_count} words per sentence (average)"
```
目前 analyzer.rb 的完整代码如下:
```ruby
lines = File.readlines("text.txt")
line_count = lines.size
text = lines.join
word_count = text.split.length
character_count = text.length
character_count_nospaces = text.gsub(/\s+/, '').length
paragraph_count = text.split(/\n\n/).length
sentence_count = text.split(/\.|\?|!/).length
puts "#{line_count} lines"
puts "#{character_count} characters"
puts "#{character_count_nospaces} characters excluding spaces"
puts "#{word_count} words"
puts "#{paragraph_count} paragraphs"
puts "#{sentence_count} sentences"
puts "#{sentence_count / paragraph_count} sentences per paragraph (average)"
puts "#{word_count / sentence_count} words per sentence (average)"
```
### 开发基础 Ruby 应用程序
#### 6. 添加额外功能
虽然我们的文本分析器已经具备了一些基本功能,但利用 Ruby 的强大功能,我们还可以从文本中提取更多有趣的数据。以下是一些可以实现的额外功能。
##### 6.1 计算“有用”单词的百分比
大多数书面材料中都包含大量虽提供上下文和结构,但并非直接有用或有趣的单词,这些单词通常被称为“停用词”。我们可以扩展应用程序,计算文本中非停用词的百分比。
首先,创建一个包含停用词的数组:
```ruby
stop_words = %w{the a by on for of are with just but and to the my I has some in}
```
下面是一个测试该概念的示例代码:
```ruby
text = %q{Los Angeles has some of the nicest weather in the country.}
stop_words = %w{the a by on for of are with just but and to the my I has some}
words = text.scan(/\w+/)
key_words = words.select { |word| !stop_words.include?(word) }
puts key_words.join(' ')
```
运行上述代码,将输出去除停用词后的单词。接下来,计算非停用词的百分比:
```ruby
((key_words.length.to_f / words.length.to_f) * 100).to_i
```
将此功能集成到 `analyzer.rb` 中,添加以下代码:
```ruby
all_words = text.scan(/\w+/)
good_words = all_words.select{ |word| !stop_words.include?(word) }
good_percentage = ((good_words.length.to_f / all_words.length.to_f) * 100).to_i
```
##### 6.2 总结文本
我们可以通过筛选出具有特定特征的句子来总结文本。假设我们要丢弃三分之一最短和三分之一最长的句子,只保留长度适中且包含特定关键词(如“is”或“are”)的句子。
创建一个新的程序 `summarize.rb`,使用以下代码:
```ruby
text = %q{
Ruby is a great programming language. It is object oriented
and has many groovy features. Some people don't like it, but that's
not our problem! It's easy to learn. It's great. To learn more about Ruby,
visit the official Ruby Web site today.
}
sentences = text.gsub(/\s+/, ' ').strip.split(/\.|\?|\!/)
sentences_sorted = sentences.sort_by { |sentence| sentence.length }
one_third = sentences_sorted.length / 3
ideal_sentences = sentences_sorted.slice(one_third, one_third + 1)
ideal_sentences = ideal_sentences.select { |sentence| sentence =~ /is|are/ }
puts ideal_sentences.join(". ")
```
代码执行流程如下:
```mermaid
graph LR
A[定义文本] --> B[分割文本为句子数组]
B --> C[按句子长度排序]
C --> D[计算三分之一的句子数量]
D --> E[提取中间三分之一的句子]
E --> F[筛选包含“is”或“are”的句子]
F --> G[输出筛选后的句子]
```
将此功能集成到 `analyzer.rb` 中,添加以下代码:
```ruby
sentences = text.gsub(/\s+/, ' ').strip.split(/\.|\?|\!/)
sentences_sorted = sentences.sort_by { |sentence| sentence.length }
one_third = sentences_sorted.length / 3
ideal_sentences = sentences_sorted.slice(one_third, one_third + 1)
ideal_sentences = ideal_sentences.select { |sentence| sentence =~ /is|are/ }
```
##### 6.3 分析其他文件
目前,我们的应用程序将文件名 `text.txt` 硬编码在其中。为了增强灵活性,我们可以在运行程序时指定要分析的文件。
Ruby 会自动将命令行参数存储在一个特殊的数组 `ARGV` 中。以下是一个测试 `ARGV` 的示例代码:
```ruby
puts ARGV.join('-')
```
从命令提示符运行 `ruby argv.rb test 123`,将输出 `test-123`。
将 `analyzer.rb` 中的 `text.txt` 替换为 `ARGV[0]`:
```ruby
lines = File.readlines(ARGV[0])
```
现在,运行 `ruby analyzer.rb text.txt` 即可分析指定的文件。
#### 7. 完成的程序
将上述所有功能集成到 `analyzer.rb` 中,最终的代码如下:
```ruby
# analyzer.rb -- Text Analyzer
stop_words = %w{the a by on for of are with just but and to the my I has some in}
lines = File.readlines(ARGV[0] || "text.txt")
line_count = lines.size
text = lines.join
# Count the characters
character_count = text.length
character_count_nospaces = text.gsub(/\s+/, '').length
# Count the words, sentences, and paragraphs
word_count = text.split.length
sentence_count = text.split(/\.|\?|!/).length
paragraph_count = text.split(/\n\n/).length
# Make a list of words in the text that aren't stop words,
# count them, and work out the percentage of non-stop words
# against all words
all_words = text.scan(/\w+/)
good_words = all_words.select{ |word| !stop_words.include?(word) }
good_percentage = ((good_words.length.to_f / all_words.length.to_f) * 100).to_i
# Summarize the text by cherry picking some choice sentences
sentences = text.gsub(/\s+/, ' ').strip.split(/\.|\?|\!/)
sentences_sorted = sentences.sort_by { |sentence| sentence.length }
one_third = sentences_sorted.length / 3
ideal_sentences = sentences_sorted.slice(one_third, one_third + 1)
ideal_sentences = ideal_sentences.select { |sentence| sentence =~ /is|are/ }
# Give the analysis back to the user
puts "#{line_count} lines"
puts "#{character_count} characters"
puts "#{character_count_nospaces} characters (excluding spaces)"
puts "#{word_count} words"
puts "#{sentence_count} sentences"
puts "#{paragraph_count} paragraphs"
puts "#{sentence_count / paragraph_count} sentences per paragraph (average)"
puts "#{word_count / sentence_count} words per sentence (average)"
puts "#{good_percentage}% of words are non-fluff words"
puts "Summary:\n\n" + ideal_sentences.join(". ")
puts "-- End of analysis"
```
使用《雾都孤儿》的文本运行完成后的 `analyzer.rb`,将得到类似以下的输出:
```plaintext
121 lines
6165 characters
5055 characters (excluding spaces)
1093 words
18 paragraphs
45 sentences
2 sentences per paragraph (average)
24 words per sentence (average)
76% of words are non-fluff words
Summary:
' The surgeon leaned over the body, and raised the left hand. Think what it is
to be a mother, there's a dear young lamb do. 'The old story,' he said, shaking
his head: 'no wedding-ring, I see. What an excellent example of the power of
dress, young Oliver Twist was. ' Apparently this consolatory perspective of a
mother's prospects failed in producing its due effect. ' The surgeon had been
sitting with his face turned towards the fire: giving the palms of his hands a
warm and a rub alternately. ' 'You needn't mind sending up to me, if the child
cries, nurse,' said the surgeon, putting on his gloves with great deliberation.
She had walked some distance, for her shoes were worn to pieces; but where
she came from, or where she was going to, nobody knows. ' He put on his hat,
and, pausing by the bed-side on his way to the door, added, 'She was a
good-looking girl, too; where did she come from
-- End of analysis
```
你可以尝试使用其他文本(如网页内容)运行 `analyzer.rb`,并根据所学知识对其功能进行改进。
#### 8. 代码注释
在源代码中,以 `#` 符号开头的文本是注释,用于帮助开发者理解代码。注释可以放在单独的行上,也可以放在代码行的末尾。以下是一些 Ruby 注释的示例:
```ruby
puts "2+2 = #{2+2}" # Adds 2+2 to make 4
# A comment on a line by itself
```
在代码中适当添加注释,可以使代码更易于理解和维护。
### 总结
通过本文,我们开发了一个完整的基础 Ruby 应用程序——文本分析器,并逐步扩展了其功能。这个应用程序展示了 Ruby 在处理大量文本和进行计算方面的强大能力。希望你能继续探索 Ruby 的更多特性,并对这个应用程序进行改进。
0
0
复制全文
相关推荐










