Ruby:File.open如何将文件作为参数传递

时间:2012-11-06 05:04:40

标签: ruby command-line-arguments

对不起,这可能是一个noob问题。这个(economic.rb)是一个解析世界经济数据的脚本。我不确定如何将xml文件传递给它。通常,为了运行这个我会做

ruby economic.rb

但是,File.open将ARGV [0]作为参数。如何在运行脚本时将xml文件( data.xml )传递给该文件。

economic.rb

require 'rubygems'
require 'nokogiri'

File.open(ARGV[0]) do |f|
  xml_doc = Nokogiri::XML::Document.parse(f)
  countries = xml_doc.css('country')
  most_populous = countries.max_by {|node| node['population'].to_i}
  puts "The most populous country in 1996 was #{most_populous['name']} with a population of #{most_populous['population']}"
  puts
  puts "The five countries with the highest inflation rate in 1996 were:"
  countries.sort_by {|country| -(country['inflation']  || 0).to_f} [0..4].each do |country|
    puts "  #{country['name']} - #{country['inflation']}%"
  end

  continent_info = countries.group_by {|country| country['continent']}
  puts
  puts "The continents and their countries in 1996 were:"
  continent_info.keys.sort.each do |continent|
    continent_info[continent].sort_by {|country|
       country['name']}.each do |country|
      puts "  #{country['name']}"
    end
  end

1 个答案:

答案 0 :(得分:5)

你可以跑:

ruby economic.rb data.xml