Ruby is awesome–lazy scripting

Sometimes I find myself doing tedious things like trying to grab the dollar amounts from text copied from the web. More and more often I turn to irb for these sort of things. For example, a few minutes ago, when I wanted to analyze my spending habits I copied the data into a file and manipulated it.

I grabbed the lines from the file

irb(main):001:0> lines = File.readlines 'transactions'


And selected those with dollar signs (with a little effort–sometimes I forget whether it is =~ or ~=).

irb(main):002:0> monies = lines.select {|l| l ~=  /\$(.*)/}
SyntaxError: compile error
(irb):2: syntax error, unexpected '='
monies = lines.select {|l| l ~=  /\$(.*)/}
                               ^
	from (irb):2
	from :0
irb(main):003:0> monies = lines.select {|l| l =~  /\$(.*)/}

Then I grabbed the numbers using map.

irb(main):008:0> nums =monies.map {|m| m.sub( /\$(.*)/,$1).to_f}

From there, I could do all sorts of things.

I could sum numbers.

 total =nums.inject(0){|sum,i|sum+i}

I could get the average.

total/nums.length

I could even see how much of the total was due to transactions under $20.

nums.reject {|i|i>20}.inject{|s,i|s+i}

In short, I like ruby.

Comments are closed.