Ruby从数组中删除非数值并将剩余值转换为浮点数

sea*_*mus 2 ruby arrays each

我有一个用户输入的字符串,我将其变成一个数组,然后遍历该数组并删除非数字值。

看起来我的正则表达式匹配工作了一半时间,而我的to_f从未将数组值设置为浮点型。

假设我输入:“ 1 2 3b c3 4,5t”

puts "Enter Minutes"  
STDOUT.flush  
freq = gets.chomp
freq = freq.split(/\W/) #this creates the array, splitting at non-word chars

p freq #outputs: ["1", "2", "3b", "c3", "4", "", "5t"]

freq.each do |minutes|
        if ( minutes == "" or /\D/.match(minutes) ) then freq.delete(minutes) else minutes.to_f end
end

p freq #outputs: ["1", "2", "c3", "4", "5t"]
Run Code Online (Sandbox Code Playgroud)

我想要的结果是:[1、2、4] #note它们是数字而不是字符

Ant*_*ony 6

问题是您仅在then条件中而不是在else条件中突变频率。

有许多可为您变异的方法,它们通常以!:结尾

freq = ["1", "2", "3b", "c3", "4", "", "5t"]
=> ["1", "2", "3b", "c3", "4", "", "5t"]

freq.reject! { |minutes| minutes.match(/\D/) || minutes == "" }.map! { |minutes| minutes.to_f }
=> [1.0, 2.0, 4.0]
Run Code Online (Sandbox Code Playgroud)

  • @seamus可以使用每个逻辑来执行任何与迭代相关的逻辑,但是如果您要利用每个块的返回值,那么使用其他可枚举的方法(例如map,reduce / each_with_object / select / reject / all?/ /?/ find / etc您可以在这里查看方法的完整列表https://ruby-doc.org/core-2.6.2/Enumerable.html (2认同)