首页 > 应用开发 > IT综合 > 将字符串数组转换为浮点数数组
我正在编写一个围绕从文件中获取数值数据集的应用程序。 但是,由于数据是以字符串形式获取的,所以我必须将其转换为浮点数,这就是有趣的开始。 我的代码的相关部分如图所示(第 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
endft.collect! {|i| i.to_f}
这在 irb 中工作得很好,也就是说,最后一行将数组更改为浮点数。
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]
但是,当我运行我的应用程序时,出现此错误:
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>'
对此的任何帮助将不胜感激。
[["1","2"],["3","4"]]
ft = []puts "File Name: #{ARGV[0]}"File.open(ARGV[0], "r") do |file|
file.each_line do |line|
ft << line.scan(/\d+/) endendtmp = []ft.each do |line|
line.each do |number|
tmp << number.to_f
endendputs tmp
ft.flatten!.collect! { |i| i.to_f }
ft = []puts "File Name: #{ARGV[0]}"File.open(ARGV[0], "r") do |file|
file.each_line do |line|
ft << line.scan(/\d+/) endendft = ft.flatten.collect { |i| i.to_f }
原文连接: 将字符串数组转换为浮点数数组
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/70016198/viewspace-2885754/ ,如需转载,请注明出处,否则将追究法律责任。