HeadFIrst Ruby 第六章总结 block return values
前言
这一章通过抽取一个文件中的确定的单词的项目进行讲解,主要包括了:
- File 的打开、阅读与关闭
- find_all & refuse方法的相关内容
- map 方法的相关内容
这章的核心是:关于 block 具有 return value to method 的功能,以及利用这个功能实现 array 中的一些遍历的操作.
File 的打开、阅读和关闭
第一种方式:使用普通方法
打开文件:review_file = File.open("review.txt")
阅读文件lines = review_file.readlines
关闭文件review_file.close
需要关闭文件的原因:
- 如果同时打开了多个文件,可能会出现错误
- 文件阅读之后,会呈现空白,因为 already read to the end of the file, and there's nothing after that.
第二种方式:使用 with a block 的方法
File.open("review.txt") do |review_file|
lines = review_file.readlines
end
使用 with a block 的方法的优点
When the block finishes, the file is automatically closed for you.
注意事项:
由于 lines 是 block 中的 variable, 因此在 method 之外使用会出现 undefined 的错误,因此,应该在使用 lines 变量之前先定义一下:lines = []
find_all 方法 & refuse 方法
find_all 方法
格式:
relevant_lines = lines.find_all do |line|
line.include?("Truncated")
end
自我实现:
relevant_lines = []
lines.each do |line|
if line.include?("Truncated")
relevant_lines << line
end
end
refuse 方法
refuse 方法与 find_all 方法相反, 其中的「自我实现」 中的 if 变为 unless
map 方法
map 方法与 find_all 方法 & refuse 方法很 similar, 它们的不同之处是:
- map 方法:add the block's return value itself to the new array
- find_all 方法 & refuse 方法: use the block's return value to decide whether to copy the original element to the new array.
格式:
adjectives = reviews.map { |review| find_adjectives(review) }
自我实现:
adjectives = []
reviews.each do |review|
adjective << find_adjective(review)
end
puts adjectives
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具