加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-17 03:15:14 所属栏目:百科 来源:网络整理
导读:对不起,这可能是一个noob问题.这(economic.rb)是一个解析世界经济数据的脚本.我不确定如何将xml文件传递给它.通常情况下,我会这样做 ruby economic.rb 但是,File.open将ARGV [0]作为参数.如何在运行脚本时将xml文件(data.xml)传递给它. economic.rb require
对不起,这可能是一个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

解决方法

你可以运行:

ruby economic.rb data.xml

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读