---
第一个脚本:比较文件清单
A First Script: Comparing File Inventories
---
#---
# Excerpted from "Everyday Scripting in Ruby"
# We make no guarantees that this code is fit for any purpose.
# Visit http://www.pragmaticprogrammer.com/titles/bmsft for more book information.
#---
def check_usage
unless ARGV.length == 2 # 注释②
puts "Usage: differences.rb old-inventory new-inventory"
exit
end
end
def boring?(line)
line.chomp.split('/').include?('temp') or
line.chomp.split('/').include?('recycler')
end
def contains?(line, key)
line.chomp.split('/').include?(key) # 注释⑥
end
def boring?(line, boring_words)
boring_words.any? do | a_boring_word | # 注释⑤
contains?(line, a_boring_word)
end
end
def inventory_from(filename)
inventory = File.open(filename)
downcased = inventory.collect do | line | # 注释③
line.downcase
end
downcased.reject do | line | # 注释④
# contains?(line, 'temp') or contains?(line, 'recycler')
boring?(line, ['temp','recycler'])
end
end
def compare_inventory_files(old_file, new_file)
old_inventory = inventory_from(old_file)
new_inventory = inventory_from(new_file)
puts "The following files have been added:"
puts new_inventory - old_inventory
puts ""
puts "The following files have been deleted:"
puts old_inventory - new_inventory
end
if $0 == __FILE__ # 注释①
check_usage
compare_inventory_files(ARGV[0], ARGV[1])
end
① $0表示在命令行里出现的运行脚本的名字, __FILE__表示脚本的名字, 如果是在命令行里运行的脚本则执行,否则什么也不做..
irb(main):001:0> __FILE__
=> "(irb)"
irb(main):002:0> $0
=> "D:/ruby/bin/fxri.rbw"
② unless意为"除非", 相当于if not..
irb(main):012:0> def check_unless(x)
irb(main):013:1> unless x==2
irb(main):014:2> puts "x does not equal 2"
irb(main):015:2> end
irb(main):016:1> end
=> nil
irb(main):017:0> check_unless(2)
=> nil
irb(main):018:0> check_unless(3)
x does not equal 2
=> nil
③ 迭代器collect: 收集代码块每次执行的值, 然后放入一个新的数组作为返回值..
irb(main):019:0> [1, 2, 3].collect do | ele |
irb(main):020:1* ele * 2
irb(main):021:1> end
=> [2, 4, 6]
④ 迭代器reject: 过滤代码块返回为真的所有元素, 然后放入一个新的数组作为返回值..
irb(main):022:0> [1, 2, 3].reject do | ele |
irb(main):023:1* ele == 2
irb(main):024:1> end
=> [1, 3]
⑤ 迭代器any: 数组中任意一个元素使得附带的代码块返回true, 则返回true..
irb(main):028:0> [1, 2, 3].any? do | ele |
irb(main):029:1* ele > 2
irb(main):030:1> end
=> true
⑥ chomp用来去掉"\n"字符..
irb(main):031:0> "end\n".chomp
=> "end"