Tuesday, August 23, 2005

A Sample Ruby Code

A few people were asking for a sample Ruby code, so here goes!

First the history - my Babylon Time Trial expired and I was looking for a good alternative with my GRE coming up. So I thought, why not code it in Ruby? So basically what my code does is, it queries the Google Search engine, uses the 'define' keyword and retrieves the page containing the definitions of the word entered at the command line. After retrieving, I use some Regular Expressions (here's where Ruby makes life sooo easy!!) to parse the page and remove the unnecessary html tags, etc and display just the definitions. The code follows ...

require 'net/http'

word = ''
text = ''
ARGV.each {|arg| word << arg; word <<" "}

res = Net::HTTP.get_response('www.google.co.in', '/search?hl=en&q=define%3A'+word+'&btnG=Google+Search&meta=')

arr = res.body.split(/<\w+>/)
arr2 = []
arr.each { |g| arr2.push(g) unless g =~ /<.+>/}
arr2.pop if arr2.last =~ /Display definitions/
arr2.clear if arr2.last =~ /all words are spelled correctly/
puts "\n#{arr2.length} Definition(s) of #{word.upcase}\n\n"
arr2.each { |d| puts d+"\n\n"}

A brief explanation of the Code -
The first line includes the net/http module.
The third line take the word(s) entered at the command line and forms a string.
The next line retrives the page using the 'define' keyword at google.
The rest of the code is just parsing the page to remove tags etc.

Here's a sample output

C:\Ruby>ruby google.rb behoove

1 Definition(s) of BEHOOVE

be appropriate or necessary; "IT behooves us to reflect on this matter"

C:\Ruby>ruby google.rb ruby programming language


Ruby is an object-oriented programming language. It combines syntax inspired by Ada and Perl with Smalltalk-like object-oriented features, and also shares some features with Python, Lisp and CLU. Ruby is an interpreted language.

I think this code shows just some of the power of Ruby - in very few lines of code, we can achieve some AWESOME functionality! Till the next post ...

P.S. Im running a server at my place, check it out at http://swapneel.no-ip.info

Its got loads of Ruby and Java Code, and i have also deployed a Ruby on Rails application on it (thats gonna be the topic of my next post). No URLs for the former, good luck searching for it!
The latter can be found at http://swapneel.no-ip.info/code


At September 15, 2005 11:07 PM, Blogger shawnflynn06298598 said...

This comment has been removed by a blog administrator.


Post a Comment

<< Home