Wednesday, 9 September 2009

My first ruby script

It's been a while since I was reading my ruby book. I end up forgetting most of what I read because I have not used it in a project. Today I needed to do some xml parsing and I always find it so clunky to do in java, so I took ruby for a spin.

For the life of me I couldn't get gems to work properly without adding in "require gems" at the top. Not sure if I needed to be setting some env var, but I figure running on XP using cygwin is a bit out of the normal ruby path.

My other complaint (if you can call it this) is that there seems to be 50 different ways to do everything. There are similar issues in java of course, but it took me a bit to find a small, clear example.

After I got through the "research" part, I found it a lot of fun for a 15 line script.

3 comments:

  1. What, no code snippet? ;-)

    ReplyDelete
  2. It dumps out a value from an xml file, and loads it into an array and then prints out the values, removing duplicates.
    It might not be pretty, but it worked.
    require 'rexml/document'
    include REXML
    files = ['file1.txt', 'file2.txt', 'file3.txt']
    files.each() { |file|
    xmlfile = File.new(file)
    xmldoc = Document.new(xmlfile)
    puts '==================='
    puts file
    collections = Array.new
    xmldoc.elements.each("K2Log/K2CollSearch/Collection") {
    |e| collections << e.text
    }
    puts collections.uniq!
    }

    ReplyDelete