1
1

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.

getsメソッドで入力された値を取得 ❏Ruby❏

Posted at

Rubyでgetsを読み込むとターミナルで入力待ちになります。
そこで入力された値を文字列として返します。

実際にやっていきやす!

getsだけだと勝手に改行されるので、それを防ぐために.chompを付けます。

sample.rb
word = gets.chomp
puts word
ターミナル
$ ruby sample.rb
## 入力待ち

Hello World!
## 適当に打ち込みenterを押すと…

Hello World!
## 結果が表示される

※あくまで文字列を返す

getsは数字を打ち込んでも文字列として返します。
数値として返したい場合は、.to_iを付けます。

sample.rb
number = gets.to_i
puts number + 3
ターミナル
$ ruby sample.rb
## 入力待ち

5
## 適当に打ち込みenterを押すと…

8
## 結果が表示される
## numberには数値が入ったことがわかる。

【結論】 文字列を期待している場合は、`gets.chomp` 数値を期待している場合は、`gets.to_i` を使う。
ではまた!
1
1
0

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?