Reputation:
I'm writing an app that revolves around getting sets of numerical data from a file. However, since the data is acquired in string form, I have to convert it to floats, which is where the fun starts. The relevant section of my code is as shown (lines 65-73):
ft = []
puts "File Name: #{ARGV[0]}"
File.open(ARGV[0], "r") do |file|
file.each_line do |line|
ft << line.scan(/\d+/)
end
end
ft.collect! {|i| i.to_f}
This works just fine in irb, that is, the last line changes the array to floats.
irb(main):001:0> ft = ["10", "23", "45"]
=> ["10", "23", "45"]
irb(main):002:0> ft.collect! {|i| i.to_f}
=> [10.0, 23.0, 45.0]
However when I run my application I get this error:
ruby-statistics.rb:73:in `block in <main>': undefined method `to_f' for #<Array:
0x50832c> (NoMethodError)
from ruby-statistics.rb:73:in `collect!'
from ruby-statistics.rb:73:in `<main>'
Any help with this would be appreciated.
Upvotes: 7
Views: 9604
Reputation: 4084
You should have a look at the format of "ft" after reading the file.
Each line gets stored in another array so in fact "ft" looks something like this:
[["1","2"],["3","4"]]
So you have to do something like this:
ft = []
puts "File Name: #{ARGV[0]}"
File.open(ARGV[0], "r") do |file|
file.each_line do |line|
ft << line.scan(/\d+/)
end
end
tmp = []
ft.each do |line|
line.each do |number|
tmp << number.to_f
end
end
puts tmp
This is just a guess since I don't know what your file format looks like.
Edit:
Here as a one-liner:
ft.flatten!.collect! { |i| i.to_f }
Upvotes: 6
Reputation: 11385
line.scan
returns an array, so you are inserting an array into an array. The easiest thing to do would be to call flatten
on the array before you convert the strings to floats.
ft = []
puts "File Name: #{ARGV[0]}"
File.open(ARGV[0], "r") do |file|
file.each_line do |line|
ft << line.scan(/\d+/)
end
end
ft = ft.flatten.collect { |i| i.to_f }
Upvotes: 12