RubyでXMLを弄る
Ruby用のXMLパーサは色々あるけれど、とりあえず現在はREXMLを利用中。しかし使い方がいまいちよくわからないので目的の要素を取り出すのにも一苦労。
今日作ってみたコード
Tryntより、身長と体重の入力値からBMI値を計算するAPIを利用し、結果のXMLをパースして出力、という単純なものを作成してみた。まだRubyならでは、というキレイな書き方が出来ないなぁと痛感。
require 'rexml/document' require 'open-uri' def usage p 'usage: ruby bmixml.rb [height(m)] [weight(kg)]' end if (ARGV.length < 2) usage end h = ARGV[0].to_f w = ARGV[1].to_f puts "h = #{h}, w = #{w}" exit if (h < 0 || w < 0) uri = 'http://www.trynt.com/body-mass-index-api/v1/' + '?' uri += 'h=' + h.to_s + '&w=' + w.to_s + '&t=metric' doc = nil begin open(uri) {|u| content = u.read doc = REXML::Document.new(content) } end bmi = doc.elements["/Trynt/Body-Mass-Index/bmi"].text summary = doc.elements["/Trynt/Body-Mass-Index/summary"].text puts 'BMI = ' + bmi + ': ' + summary
結果は、以下のようにすごく単純なもの。こんな計算ローカルだけでしろと普通は思うでしょうが。
$ ruby bmixml.rb 1.76 61 BMI = 20: Normal Weight