加载中...

习题 20: 函式和档案


回忆一下函式的要点,然后一边做这节练习,一边注意一下函式和档案是如何一起协作发挥作用的。

  1. input_file = ARGV[0]
  2. def print_all(f)
  3. puts f.read()
  4. end
  5. def rewind(f)
  6. f.seek(0, IO::SEEK_SET)
  7. end
  8. def print_a_line(line_count, f)
  9. puts "#{line_count} #{f.readline()}"
  10. end
  11. current_file = File.open(input_file)
  12. puts "First let's print the whole file:"
  13. puts # a blank line
  14. print_all(current_file)
  15. puts "Now let's rewind, kind of like a tape."
  16. rewind(current_file)
  17. puts "Let's print three lines:"
  18. current_line = 1
  19. print_a_line(current_line, current_file)
  20. current_line = current_line + 1
  21. print_a_line(current_line, current_file)
  22. current_line = current_line + 1
  23. print_a_line(current_line, current_file)

特别注意一下,每次运行 print_a_line 时,我们是怎样传递当前的行号资讯的。

你应该看到的结果

  1. $ ruby ex20.rb test.txt
  2. First let's print the whole file:
  3. To all the people out there.
  4. I say I don't like my hair.
  5. I need to shave it off.
  6. Now let's rewind, kind of like a tape.
  7. Let's print three lines:
  8. 1 To all the people out there.
  9. 2 I say I don't like my hair.
  10. 3 I need to shave it off.
  11. $

加分习题

  1. 通读脚本,在每行之前加上注解,以理解脚本里发生的事情。
  2. 每次 print_a_line 运行时,你都传递了一个叫 current_line的变量。在每次呼叫函数时,印出 current_line 的值,跟踪一下它在 print_a_line 中是怎样变成 line_count 的。
  3. 找出脚本中每一个用到函式的地方。检查 def 一行,确认参数没有用错。
  4. 上网研究一下 file 中的 seek 函数是做什么用的。试着运行 ri file 看看能不能从 rdoc 中学到更多。
  5. 研究一下 += 这个简写操作符号的作用,写一个脚本,把这个操作符号用在里边试一下。

还没有评论.