活动介绍

开发基础Ruby应用程序

立即解锁
发布时间: 2025-08-20 01:30:30 阅读量: 2 订阅数: 3
PDF

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 的更多特性,并对这个应用程序进行改进。
corwn 最低0.47元/天 解锁专栏
赠100次下载
点击查看下一篇
profit 400次 会员资源下载次数
profit 300万+ 优质博客文章
profit 1000万+ 优质下载资源
profit 1000万+ 优质文库回答
复制全文

相关推荐

张诚01

知名公司技术专家
09级浙大计算机硕士,曾在多个知名公司担任技术专家和团队领导,有超过10年的前端和移动开发经验,主导过多个大型项目的开发和优化,精通React、Vue等主流前端框架。
最低0.47元/天 解锁专栏
赠100次下载
百万级 高质量VIP文章无限畅学
千万级 优质资源任意下载
千万级 优质文库回答免费看

最新推荐

【调试与性能优化】:LMS滤波器在Verilog中的实现技巧

![【调试与性能优化】:LMS滤波器在Verilog中的实现技巧](https://img-blog.csdnimg.cn/img_convert/b111b02c2bac6554e8f57536c89f3c05.png) # 摘要 本文详细探讨了最小均方(LMS)滤波器的理论基础、硬件实现、调试技巧以及性能优化策略,并通过实际案例分析展示了其在信号处理中的应用。LMS滤波器作为一种自适应滤波器,在数字信号处理领域具有重要地位。通过理论章节,我们阐述了LMS算法的工作原理和数学模型,以及数字信号处理的基础知识。接着,文章介绍了LMS滤波器的Verilog实现,包括Verilog语言基础、模块

【机器人灵巧手自学习能力】:AI在抓取技术中的应用探索

![AI自学习能力](https://ai-kenkyujo.com/wp-content/uploads/2021/08/29-2-%E6%95%99%E5%B8%AB%E3%81%AA%E3%81%97%E5%AD%A6%E7%BF%92%E3%81%A8%E3%81%AF_%E4%BF%AE%E6%AD%A3.png.webp) # 摘要 机器人灵巧手的自学习能力是近年来机器人技术领域中一个快速发展的研究领域。本文首先概述了自学习能力的基本概念及其在机器人技术中的重要性。接着,深入探讨了自学习技术的理论基础,包括自学习机制的基本原理、算法选择以及系统的训练与评估方法。在第三章中,文章详

【Matlab优化算法实战】:精通Matlab实现复杂问题优化的技巧

![【Matlab优化算法实战】:精通Matlab实现复杂问题优化的技巧](https://img-blog.csdnimg.cn/baf501c9d2d14136a29534d2648d6553.png?x-oss-process=image/watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBA5Zyo6Lev5LiK77yM5q2j5Ye65Y-R,size_20,color_FFFFFF,t_70,g_se,x_16) # 摘要 本文全面概述了Matlab优化算法的理论基础、实践操作以及高级应用。首先,介绍了数学优化问题的分类和优化

Simulink专家指南:OFDM模型构建与调试的终极技巧

![Simulink专家指南:OFDM模型构建与调试的终极技巧](https://de.mathworks.com/company/technical-articles/wireless-transceiver-design-and-network-modeling-in-simulink/_jcr_content/mainParsys/image_1354781049_cop.adapt.full.medium.jpg/1714297948399.jpg) # 摘要 本文对Simulink环境下正交频分复用(OFDM)模型的构建、调试和应用进行了系统性阐述。首先介绍了Simulink基础与

构建可扩展医疗设备集成方案:飞利浦监护仪接口扩展性深入解析

![构建可扩展医疗设备集成方案:飞利浦监护仪接口扩展性深入解析](https://media.licdn.com/dms/image/D4D12AQHs8vpuNtEapQ/article-cover_image-shrink_600_2000/0/1679296168885?e=2147483647&v=beta&t=NtAWpRD677ArMOJ_LdtU96A1FdowU-FibtK8lMrDcsQ) # 摘要 本文探讨了医疗设备集成的重要性和面临的挑战,重点分析了飞利浦监护仪接口技术的基础以及可扩展集成方案的理论框架。通过研究监护仪接口的技术规格、数据管理和标准化兼容性,本文阐述了实

【C#跨平台开发与Focas1_2 SDK】:打造跨平台CNC应用的终极指南

![Focas1_2 SDK](https://www.3a0598.com/uploadfile/2023/0419/20230419114643333.png) # 摘要 本文全面介绍了C#跨平台开发的原理与实践,从基础知识到高级应用,详细阐述了C#语言核心概念、.NET Core与Mono平台的对比、跨平台工具和库的选择。通过详细解读Focas1_2 SDK的功能与集成方法,本文提供了构建跨平台CNC应用的深入指南,涵盖CNC通信协议的设计、跨平台用户界面的开发以及部署与性能优化策略。实践案例分析部分则通过迁移现有应用和开发新应用的实战经验,向读者展示了具体的技术应用场景。最后,本文对

STM8点阵屏汉字显示:用户界面设计与体验优化的终极指南

![STM8点阵屏汉字显示:用户界面设计与体验优化的终极指南](http://microcontrollerslab.com/wp-content/uploads/2023/06/select-PC13-as-an-external-interrupt-source-STM32CubeIDE.jpg) # 摘要 STM8点阵屏技术作为一种重要的显示解决方案,广泛应用于嵌入式系统和用户界面设计中。本文首先介绍STM8点阵屏的技术基础,然后深入探讨汉字显示的原理,并着重分析用户界面设计策略,包括布局技巧、字体选择、用户交互逻辑及动态效果实现等。接着,本文详细阐述了STM8点阵屏的编程实践,涵盖开

【游戏物理引擎基础】:迷宫游戏中的物理效果实现

![基于C++-EasyX编写的益智迷宫小游戏项目源码.zip](https://images-wixmp-ed30a86b8c4ca887773594c2.wixmp.com/f/7eae7ef4-7fbf-4de2-b153-48a18c117e42/d9ytliu-34edfe51-a0eb-4516-a9d0-020c77a80aff.png/v1/fill/w_1024,h_547,q_80,strp/snap_2016_04_13_at_08_40_10_by_draconianrain_d9ytliu-fullview.jpg?token=eyJ0eXAiOiJKV1QiLCJh

【wxWidgets多媒体处理】:实现跨平台音频与视频播放

![【wxWidgets多媒体处理】:实现跨平台音频与视频播放](https://media.licdn.com/dms/image/D4D12AQH6dGtXzzYAKQ/article-cover_image-shrink_600_2000/0/1708803555419?e=2147483647&v=beta&t=m_fxE5WkzNZ45RAzU2jeNFZXiv-kqqsPDlcARrwDp8Y) # 摘要 本文详细探讨了基于wxWidgets的跨平台多媒体开发,涵盖了多媒体处理的基础理论知识、在wxWidgets中的实践应用,以及相关应用的优化与调试方法。首先介绍多媒体数据类型与

【BT-audio音频抓取工具比较】:主流工具功能对比与选择指南

# 摘要 本文旨在全面介绍BT-audio音频抓取工具,从理论基础、功能对比、实践应用到安全性与隐私保护等多个维度进行了深入探讨。通过分析音频信号的原理与格式、抓取工具的工作机制以及相关法律和伦理问题,本文详细阐述了不同音频抓取工具的技术特点和抓取效率。实践应用章节进一步讲解了音频抓取在不同场景中的应用方法和技巧,并提供了故障排除的指导。在讨论工具安全性与隐私保护时,强调了用户数据安全的重要性和提高工具安全性的策略。最后,本文对音频抓取工具的未来发展和市场需求进行了展望,并提出了选择合适工具的建议。整体而言,本文为音频抓取工具的用户提供了一个全面的参考资料和指导手册。 # 关键字 音频抓取;