7
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Rubyで標準入力をチェックする

Last updated at Posted at 2015-07-01

標準入力で入力された値をチェックしたい場合は、こう書くとできます。

check.rb
def is_num
  loop do
    print ">> "
    i = $stdin.gets.chomp
    return i if i =~ /^\d+$/
    puts "数字で入力してください"
  end
end

puts is_num + "が入力されました"

この例で言うと数字チェックですが、/^\d+$/となっている正規表現の部分を変更することで、いろいろなチェックが可能になります。

コツとしては入力をloopで待ち受けることと、chompで入力された値の改行を取り除いておくことでしょうか。

7
8
5

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
7
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?