我有一个用户输入的字符串,我将其变成一个数组,然后遍历该数组并删除非数字值。
看起来我的正则表达式匹配工作了一半时间,而我的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它们是数字而不是字符
问题是您仅在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)