Monday, March 27, 2006

Ruby is Fun!

It's like writing NewtonScript again, only better. Object oriented, clean syntax, and it's really easy to string useful method calls together as if building up a UNIX shell incantation with pipes. I've only learned a little of the syntax and already I often find I can guess what operator might work to do whatever operation I need next. Just ask yourself what would be the most natural Ruby way to do that, and sure enough that's the way it's done. Plus, irb reminds me of the glorious Newton Inspector - it is so gosh-darned easy to try everything out in small chunks and look at your data structures as you go along! Wheeeeee!

I was once asked in an interview to write a program to reverse the order of the words in a string. The algorithmic insight is that if you have a "reverse" operation you can apply it to the whole string, then to each individual word which is now in the correct place. But in C you still need some scaffolding to do that. In Ruby? Not so much. Any job like that is an obvious one-liner. It can probably be done shorter than this, but here's the first incantation I came up with:

str.reverse.split.map{|o| o.reverse+" "}.join

That says take the string "str", reverse the characters, split the result into an array of strings (the default separator is whitespace so I don't need to specify that), reverse each object in the array and add a space on the end (returning the modified array), join the array of small strings back into one big string, and return that result. Toss in a print statement and you're done.

Oh, wait. We're supposed to take lines from standard input. Okay:

#!/usr/local/bin/ruby
ARGF.each {|line|
puts line.reverse.split.map{|o| o.reverse+" " }.join
}


Are we having fun yet?

UPDATE: "reverse" operates on arrays so there's no need to do TWO reverses; I can just split the string into an array, reverse the items in the array, and rejoin to output the string. Also, I can have join put the spaces back in. Thus, this works:

puts str.split.reverse.join(" ")

if str="Now is the time.", that outputs "time. the is Now".

0 Comments:

Post a Comment

<< Home

Performancing