From: Martin DeMello Date: 2007-03-16T07:05:13+09:00 Subject: Re: Need help converting Perl to Ruby (detecting integers and decimals in strings) On 3/16/07, Martin DeMello wrote: > On 3/16/07, Paul wrote: > > > > Background context: @rawfields is an array that holds the contents of > > an imported line from a text file. Here are some sample lines from > > the input file: > > --- > > "0" "0" "0" "0" "0" "0" "Bar" > > "5.66666" "0" "3.566662" "1.383332" "6" "0" "Foo" > > >> rawfields = ["5.66666", "0", "3.566662", "1.383332", "6", "0", "Foo"] > => ["5.66666", "0", "3.566662", "1.383332", "6", "0", "Foo"] > > >> rawfields.map {|field| "%0.2f" % Float(field) rescue field} > => ["5.67", "0.00", "3.57", "1.38", "6.00", "0.00", "Foo"] oops - missed the fact that you didn't want integers converted into decimals. Best way I can think of is a two level try/rescue-try/rescue >> rawfields.map {|field| "%d" % Integer(field) rescue "%0.2f" % Float(field) rescue field} => ["5.67", "0", "3.57", "1.38", "6", "0", "Foo"] More explicitly rawfields.map do |field| begin "%d" % Integer(field) rescue begin "%0.2f" % Float(field) rescue field end end end martin