LoginSignup
2
1

More than 5 years have passed since last update.

io.getsで得た文字列をそのまま文字列比較してもマッチしない理由

Last updated at Posted at 2015-12-10

io.getsでは最後に改行文字が入る

Rubyでの標準入力メソッドであるio.getsを使って文字列を取得すると、最後に改行コードが付与されます

普段からputsを使っていると、改行文字が出力されないので気づかずハマってしまいます。
printを使うと、しっかり\nが付与されてることが確認できます。

print_test.rb
input = gets
print "print with puts: "
puts input
print "print with p: "
p input
出力結果
> ruby
print with puts: ruby
print with p: "ruby\n"

比較する前にString#chompで改行コードを取り除こう

このため直接文字列比較をするとマッチしません。
String#chompを使って最後の改行文字を取り除いてから比較しましょう。

gets_and_chomp.rb
input = gets
puts input == "ruby"
puts input.chomp == "ruby"
出力結果
> ruby
false
true
2
1
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1