ユーザーが入力した文字列を配列に変換してから、配列を反復処理して数値以外の値を削除します。
正規表現の一致が半分の時間で機能しているようで、to_fが配列値をfloatに設定することはありません。
「12 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]
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加