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?
require ‘scanf’
File.open(“filename”) do |fh|
fh.scanf("%f%f%f%f") {|n| n }
end
The point of the {|n| n} is to force a capture of each set of numbers,
using the block form of scanf. If you’re not sure how many numbers
are on each line, you’d have to do a little more work but scanf might
still be a good option.
David
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.