[lnkForumImage]
TotalShareware - Download Free Software

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


 

Forums >

comp.lang.ruby

how to convert string into number

Li Chen

7/5/2007 10:37:00 PM

Hi all,

I read several rows of numbers and split each row into an array. I get
an array of array. By default Ruby treat each number as a string. I want
to convert each string into a number. The only way I can think of is to
loop through the old array of array, change each element in each row
using #to_f and put them back into a new array. It is not efficient.
What other options might be better?

Thanks,

Li

# file format

1 100 33 32
2 500 33 20

....

--
Posted via http://www.ruby-....

3 Answers

Detlef Reichl

7/5/2007 10:50:00 PM

0

Hi,

i would do it like this:


array = []

yourfile.each_line{|line| array << line.split(' ').collect(|item| item.to_f)}


Cheers
detlef

Am Freitag, den 06.07.2007, 07:36 +0900 schrieb Guest:
> Hi all,
>
> I read several rows of numbers and split each row into an array. I get
> an array of array. By default Ruby treat each number as a string. I want
> to convert each string into a number. The only way I can think of is to
> loop through the old array of array, change each element in each row
> using #to_f and put them back into a new array. It is not efficient.
> What other options might be better?
>
> Thanks,
>
> Li
>
> # file format
>
> 1 100 33 32
> 2 500 33 20
>
> ....
>


Bill Kelly

7/5/2007 10:50:00 PM

0

From: "Guest" <chen_li3@yahoo.com>
>
> I read several rows of numbers and split each row into an array. I get
> an array of array. By default Ruby treat each number as a string. I want
> to convert each string into a number. The only way I can think of is to
> loop through the old array of array, change each element in each row
> using #to_f and put them back into a new array. It is not efficient.
> What other options might be better?
>
> Thanks,
>
> Li
>
> # file format
>
> 1 100 33 32
> 2 500 33 20

One way would be to use #map:

irb(main):013:0> rows = [["1", "100", "33", "32"], ["2", "500", "33", "20"]]
=> [["1", "100", "33", "32"], ["2", "500", "33", "20"]]

irb(main):014:0> rows.each {|row| row.map! {|c| c.to_f} }
=> [[1.0, 100.0, 33.0, 32.0], [2.0, 500.0, 33.0, 20.0]]

You could also use #to_i if you wanted integers.


Hope this helps,

Bill



dblack

7/5/2007 11:12:00 PM

0