Ruby Quiz: Unit Conversions
November 20th, 2008
November 20th, 2008
I decided to join Ruby Quiz for the first time ever - I am realizing that I am extremely late to jump on the RQ bandwagon - but hey, is still better later than never. I have chosen a funny moment though: it’s a quiz everyone was excited about, but almost nobody solved (2 solutions so far except mine, which is maybe the lowest number of solvers ever). So here’s the quiz:
Your task is to write a units converter script. The input to the
script must be three arguments: the quantity, the source units, and
the destination units. The first example above would be run like this:
$ ruby convert.rb 50 miles kilometers
Or, using abbreviations:
$ ruby convert.rb 50 mi km
Support as many units and categories of units (i.e. volume, length,
weight, etc.) as you can, along with appropriate abbreviations for
each unit.
and my solution:
- require ‘rubygems’
- require ‘cgi’
- require ’scrubyt’
- begin
- google_converter = Scrubyt::Extractor.define do
- fetch "http://www.google.com/search?q=#{CGI::escape(ARGV[0])}+#{CGI::escape(ARGV[1])}+to+#{CGI::escape(ARGV[2])}"
- google_result "//td[@dir='ltr']" do
- final_result(/= (.+) /)
- end
- end
- puts google_converter.to_hash[0][:final_result]
- rescue
- puts "Sorry, even *google* can’t translate that!"
- end
Examples:
ex: ruby converter.rb 10 "meter per second" "mile per hour" 22.3693629 ruby converter.rb 10 USD EUR 7.91201836 ruby converter.rb 7 "ruby gems" "python eggs" Sorry, even *google* can't translate that!
The biggest downside of the proposed solution is that you need to be on-line. However, nowadays, when this is almost the norm, the advantages outweigh this in my opinion:
- Support for a lot of conversions (I doubt anyone can offer a much richer database of units than google) including their abbreviations
- Up-to-date conversions: for example currency conversion
- Very robust error handling - outsourced to google! Hard to beat that…

November 20th, 2008 at 11:15 am
hehehe
a bit cheating, but i guess it is ok
November 20th, 2008 at 2:57 pm
If you are going to do that, you might as well just use one of the gems that can do unit conversion (like ruby-units, or facets).
require ‘rubygems’
require ‘ruby-units’
‘10 m/s’.to(’mph’) #=>22.3694 mph
the benefit here is that you get a real object you can use like a numeric, which you can do additional math on.
November 20th, 2008 at 3:57 pm
I heard converting strings to objects is impossible.
November 23rd, 2008 at 2:09 pm
@anon: I heard ruby’s string is already object
February 16th, 2009 at 12:32 am
@Kevin
The issue with ruby-units is that it fails on mixed units. i.e. if I have a string “7 lb 2 oz”, and I’d like to find out how many ounces that is equivalent to, ruby-units isn’t happy at all. Google, on the other hand, is