From: Josef 'Jupp' SCHUGT Date: 2004-03-12T05:58:37+09:00 Subject: Re: Novice question, tranlate awk code to ruby code Hi! * Horacio Castellini: > I'm a novice ruby user, but ancient user in Linux world. We assume > have a data file with two data field in two columns. In awk program > when I like time them a script code may be: > > { > print $1*$2 > } > > for example I can use "% cat foo.dat|awk -f times.awk" d'accorde. > Well, how can I do this in ruby code? First some remark on the above command line: It is unnecessarily complicated, awk '{print $1 * $2}' times.awk works as well. Two solutions using Ruby. First one does integer arithmetics: ruby -a -n -e 'puts $F[0].to_i * $F[1].to_i' Second one does floating-point arithmetics: ruby -a -n -e 'puts $F[0].to_f * $F[1].to_f' They only differ in the type conversion part. '-e' means that what follows is code to be executed. '-n' makes the Ruby iterate over all lines successively assigning them to $_ '-a' makes Ruby split $_ into its parts assigning the result to $F which is an array of strings To specify the column separator you can use the '-F' option that is familiar from awk. Please note that awk's $0 maps to Ruby's $_ and that $1, $2, ... map to $F[0], $F[1], ... HTH, Josef 'Jupp' SCHUGT -- E-Mail: .--- ..- .--. .--. .--.-. --. -- -..- .-.-.- -.. . http://oss.erdfunkstelle.de/ruby/ - German comp.lang.ruby FAQ http://rubyforge.org/users/jupp/ - Ruby projects at Rubyforge .- .-.