Better one liner to sum a column?

S

Sammyo

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
 
R

Ross Bamford

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
 
R

Robert Klemme

Ross said:
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
 
W

William James

Sammyo said:
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 }'
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,767
Messages
2,569,573
Members
45,046
Latest member
Gavizuho

Latest Threads

Top