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…
hehehe
a bit cheating, but i guess it is ok
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.
I heard converting strings to objects is impossible.
@anon: I heard ruby’s string is already object 😉
@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 🙂
Definitely imagine that that you said. Your favorite justification appeared
to be on the web the simplest thing to understand of.
I say to you, I certainly get annoyed whilst people consider
issues that they plainly do not know about.
You managed to hit the nail upon the top and defined out the entire thing without having side-effects , other folks can take a signal.
Will likely be again to get more. Thank you