0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

入力を受け取る

Rubys = gets.chomp

意味

  • gets → キーボード入力を受け取る
  • chomp → 改行(\n)を消す
    ユーザーが入力した文字をそのまま使える状態にする

1文字だけ取り出す(インデックス)

Rubys[番号その他の行を表示する]

ルール(0から始まる)

何文字 目書き方
1文字目 s[0]
2文字目 s[1]
3文字目 s[2]

Rubys = "neko"puts s[1]
# → e

複数文字を取り出す(slice)

Rubys[開始位置, 文字数]

Rubys = "programming"puts s[0]
# → pro

別の書き方(同じ意味)

Rubys.slice(0, 3)
# → s[0, 3] と同じ

まとめ(超重要ポイント)

  • 入力 → gets.chomp
  • 1文字 → s[番号]
  • 複数文字 → s[開始, 長さ]

具体例まとめ

Rubys = gets.chomp
puts s[0]
# 1文字目puts s[1]    
# 2文字目puts s[0,3]  
# 先頭3文字``その他の行を表示する

入力した文字数を数える

s = gets.chomp
puts s.length

s.length → 文字列の長さを取得する

数字をバラして整数にする

a, b = gets.split.map(&:to_i)

gets

1行入力を受け取る

10 3

 "10 3" になる

split

スペースで区切る。

Ruby"10 3".split
#=> ["10", "3"]

#デフォルトだと「スペース(空白)」で区切るけど、自分で区切り文字を指定できる!
str = "apple,orange,banana"
p str.split(",")

map(&:to_i)

それぞれを整数にする

Ruby["10", "3"].map(&:to_i)
#=> [10, 3]

※ &:to_i は「全部に to_i を適用する」という意味

a, b =

配列の中身を分けて代入

Ruby[10, 3]  a = 10, b = 3その他の行を表示する

全体の流れ

"10 3"
  gets
"10 3"
  split
["10", "3"]
  map(&:to_i)
[10, 3]
  a, b =
a = 10
b = 3

まとめ

Rubya, b = gets.split.map(&:to_i)

「1行の入力を2つの整数に分ける」

最短暗記

gets.split.map(&:to_i) = 「数字をバラして整数に」

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?