Skip to content

Instantly share code, notes, and snippets.

@louis-wu
Created April 20, 2010 04:57
Show Gist options
  • Save louis-wu/372051 to your computer and use it in GitHub Desktop.
Save louis-wu/372051 to your computer and use it in GitHub Desktop.
inventory difference
#---
# 该程序是经典的文件操作程序。
# 在shell里运行:ruby exercise-difference.rb new-inventory.txt old-inventory.txt
#---
#检查运行本程序的参数是否设置正确
def check_usage # (1)
unless ARGV.length == 2
puts "Usage: differences.rb old-inventory new-inventory"
exit
end
end
#判断是否包含temp或recycler文件夹。
def boring?(line)
line.split('/').include?('temp') or
line.split('/').include?('recycler')
end
#用collect和reject方法来生成文件序列
def inventory_from(filename)
inventory = File.open(filename)
downcased = inventory.collect do | line |
line.chomp.downcase
end
downcased.reject do | line |
boring?(line)
end
end
#比较2个文件序列的差异
def compare_inventory_files(old_file, new_file) # (2)
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 I am the script running at the command line, check_usage and compare_inventory_files
if $0 == __FILE__ # (3)
check_usage
compare_inventory_files(ARGV[0], ARGV[1])
end
#---
#该程序打印出当前文件夹及其子文件夹的所有文件。
#你可以在textmate编辑器里按ctrl+R,看到程序运行的结果。
#在shell里运行$ruby inventory.rb > new-inventory.txt, 即在当前文件夹里生成txt文件。
#---
puts Dir.glob('**/*').each { | file | file.downcase }.sort
@louis-wu
Copy link
Author

Enumerable是File对象的ancestors, 所以可以利用collect的方法。collect方法对文件里的每一行进行操作,结果返回一个array。

File.ancestors
=> [File, IO, File::Constants, Enumerable, Object, Kernel]

@louis-wu
Copy link
Author

Variable $0 holds the name of the running script as it appeared on the command line. FILE is the name of the file it appears in.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment