The Artima Developer Community
Sponsored Link

Ruby Buzz Forum
When Code Flows Like Poetry

0 replies on 1 page.

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 0 replies on 1 page
Premshree Pillai

Posts: 478
Nickname: premshree
Registered: Mar, 2004

Premshree Pillai is a Ruby evangelist, working with Yahoo!.
When Code Flows Like Poetry Posted: Jan 29, 2006 2:28 AM
Reply to this message Reply

This post originated from an RSS feed registered with Ruby Buzz by Premshree Pillai.
Original Post: When Code Flows Like Poetry
Feed Title: Premshree's Personal Weblog
Feed URL: http://premshree.livejournal.com/data/rss
Feed Description: Premshree's Weblog
Latest Ruby Buzz Posts
Latest Ruby Buzz Posts by Premshree Pillai
Latest Posts From Premshree's Personal Weblog

Advertisement

It’s not always that you get to solve complex problems. Many a time you need to implement something—something that you know is silly enough. How do you feel? Bored, I know. However, there’s small amount of joy you get when the “tool” you use lets you be creative. (Of course, there’s a distinction between the larger problem at hand and the smallest implementable part of it; it is the typically joyless implementation of this small part that I’m talking about.)

I had a situation where I had to read a data file that had on each line data like thus:

foo:bar

Obviously, you want to hold all that data in a hash. Implementing this in a typical programming language would, in pseudocode, look something like thus:

data = file("data.txt").read
hsh = {}
foreach line in data do
        k, v = line.split(":")
        hsh["k"] = v
end

Simple enough, but boring too. With Ruby, I can play:

hsh = Hash.new
File.open("test.txt").readlines.each { |line|
        hsh = hsh.update(Hash[ *line.split(":").
                map { |ele| ele = ele.match(/(.*)\n/)[1] rescue ele }.insert_nil        ])
}

The Ruby code flows like poetry. Literally. There’s an extremely elegant solution, like why pointed out to me:

Hash[*IO.read('test.txt').scan(/^(.+?):(.*)/).flatten]

But then I’d say there are no blocks there. :-)

There are many such Ruby gems scattered all around. I’ll point you to some of them I found on RedHanded:

Go use a better tool, if you can.

Read: When Code Flows Like Poetry

Topic: Oniguruma (Ruby with Demon wheels) Previous Topic   Next Topic Topic: ADV: Build virtual Tower of Babel with pixel advertising

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use