[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Better one liner to sum a column?

samuel.murphy

5/18/2006 2:51:00 PM

Is there a cleaner way to do this?

$ cat example_data
1 foo 3943
2 bar 8989
3 baz 9088

$ ruby -e 'i=0;ARGF.each{|l| i += l.split[2].to_i};p i' example_data
22020

As a relative newby I tried inject which seemed cool but
converting from string to int seem defeated that approach.

-sam

3 Answers

Ross Bamford

5/18/2006 3:10:00 PM

0

On Thu, 18 May 2006 15:51:26 +0100, Sammyo <samuel.murphy@gmail.com> wrote:

> Is there a cleaner way to do this?
>
> $ cat example_data
> 1 foo 3943
> 2 bar 8989
> 3 baz 9088
>
> $ ruby -e 'i=0;ARGF.each{|l| i += l.split[2].to_i};p i' example_data
> 22020
>
> As a relative newby I tried inject which seemed cool but
> converting from string to int seem defeated that approach.
>

How about:

$ ruby -e 'p ARGF.inject(0){|a,b|a+b.split[2].to_i}' example_data
22020

--
Ross Bamford - rosco@roscopeco.remove.co.uk

Robert Klemme

5/18/2006 9:08:00 PM

0

Ross Bamford wrote:
> On Thu, 18 May 2006 15:51:26 +0100, Sammyo <samuel.murphy@gmail.com> wrote:
>
>> Is there a cleaner way to do this?
>>
>> $ cat example_data
>> 1 foo 3943
>> 2 bar 8989
>> 3 baz 9088
>>
>> $ ruby -e 'i=0;ARGF.each{|l| i += l.split[2].to_i};p i' example_data
>> 22020
>>
>> As a relative newby I tried inject which seemed cool but
>> converting from string to int seem defeated that approach.
>>
>
> How about:
>
> $ ruby -e 'p ARGF.inject(0){|a,b|a+b.split[2].to_i}' example_data
> 22020
>
You can also do it awk style:

robert@fussel /cygdrive/c/Temp
$ cat dat
1 foo 100
2 bar 32
3 xxx 982

robert@fussel /cygdrive/c/Temp
$ ruby -nae 'BEGIN {$s=0}; $s+=$F[2].to_i; END {puts $s}' dat
1114

Kind regards

robert

William James

5/22/2006 7:06:00 PM

0

Sammyo wrote:
> Is there a cleaner way to do this?
>
> $ cat example_data
> 1 foo 3943
> 2 bar 8989
> 3 baz 9088
>
> $ ruby -e 'i=0;ARGF.each{|l| i += l.split[2].to_i};p i' example_data
> 22020
>
> As a relative newby I tried inject which seemed cool but
> converting from string to int seem defeated that approach.
>
> -sam

ruby -e 'puts $<.inject(0){|n,s| n + s[/\d+$/].to_i }'