88Pro Thinking

cat /senthoor/mind | grep thought > blog

Sunday, September 11, 2005

Palindrome - Ruby way

1. Open File
2. Sort the file
3. Read each entry
4. Strip each entry
5. Check entry equals to reverse of it (Palindrome)
6. Check length is greater than 5
7. Print it
File.open("dic-0294.txt").each{|line| puts line if (line.strip! == line.reverse and line.length>=5 )}

Couple of observations, what’s the difference between strip! and strip method. Ruby’s convention says that if a method ends with an exclamation mark (!) it has side effect (Dangerous?). strip! changes the string itself where strip returns the results but doesn’t change the string (like Java). In my case I don’t want to issue a strip command every time I use line so first time use it with !.

Also in the code there are no loop constructs and this is achieved by usage of blocks in Ruby. If you want to get a better understanding of Blocks, let me point here, here and here.

How many lines it would take to write this in Java?

posted by 88Pro / Sunday, September 11, 2005

This page is powered by Blogger. Isn't yours?

doteasy.com - free web hosting. Free hosting with no banners.