yuuki blog

プログラミング をアプトプットしています。

Ruby スペルチェック

英単語を参照するプログラムです。

条件
  • n回調べる
  • 正解と回答を配列で入力する
  • 全一致と1文字間違いのみ出力する
  • 文字の長さ間違い、2文字以上の間違いは出力しない
puts "何回調べますか?"
n = gets.to_i
puts "正解 回答の順で入力してください"
str = n.times.map{gets.chomp.split.map(&:to_s)}
for spell in str do
  i = 0
  u = 0
  if spell[0] == spell[1]
    puts "#{spell[1]}は合っています"
  elsif spell[0].length == spell[1].length
    s = spell[0].chars.each_slice(1).map(&:join)
    t = spell[1].chars.each_slice(1).map(&:join)
    spell[0].length.times do
      unless s[i] == t[i]
        u += 1
      end 
      i += 1
    end
    if u == 1
      puts "#{spell[1]}は一文字間違いです"
    end
  end
end
  • 完全一致ではなければ文字の長さを比べ、合っていれば一文字ずつの配列にする。
  • 1文字ずつ参照し、合っていなければu に1を足します。
  • uが1ならば出力します