HeadFIrst Ruby 第六章总结 block return values

前言

这一章通过抽取一个文件中的确定的单词的项目进行讲解,主要包括了:

  1. File 的打开、阅读与关闭
  2. find_all & refuse方法的相关内容
  3. map 方法的相关内容
    这章的核心是:关于 block 具有 return value to method 的功能,以及利用这个功能实现 array 中的一些遍历的操作.

File 的打开、阅读和关闭

第一种方式:使用普通方法

打开文件:review_file = File.open("review.txt")
阅读文件lines = review_file.readlines
关闭文件review_file.close

需要关闭文件的原因:

  1. 如果同时打开了多个文件,可能会出现错误
  2. 文件阅读之后,会呈现空白,因为 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




原文地址:https://www.cnblogs.com/FBsharl/p/10525676.html