我有一个用户输入的字符串,我把它转换成一个数组,然后遍历数组并删除非数字值。
看起来我的regex匹配工作了一半时间,而我的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"]

我想要的结果是:[1,2,4]注意它们是数字而不是字符

最佳答案

问题是你只在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]

关于arrays - Ruby从数组中删除非数值并将剩余值转换为浮点数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55894107/

10-11 11:10