1
1

【Ruby】標準入力から値を受け取る

Last updated at Posted at 2022-10-29

数値

入力値
7
i = gets.to_i
p i * 10
結果
70

文字列

入力値
AAA
s = gets.chomp
p s
結果
"AAA"

1行に複数の入力(半角スペース区切り)

入力値
50 100 200

配列で返す場合

arr = gets.split.map(&:to_i)
p arr
結果
[50, 100, 200]

変数に格納する場合

n1, n2, n3 = gets.split.map(&:to_i)
p n1
p n2
p n3
結果
50
100
200

文字列の場合、.map(&:to_i)が不要

複数行の入力

数値

入力値
5000
3

配列で返す場合

lines = 2.times.map { gets.to_i }
p lines
lines = readlines.map(&:to_i)
p lines
結果
[5000, 3]

変数に格納する場合

n1, n2 = 2.times.map { gets.to_i }
p n1
p n2
n1, n2 = readlines.map(&:to_i)
p n1
p n2
結果
5000
3

文字列

入力値
Ruby
Python
Java

配列で返す場合

lines = 3.times.map { gets.chomp }
p lines
lines = readlines.map(&:chomp)
p lines
結果
["Ruby", "Python", "Java"]

変数に格納する場合

s1, s2, s3 = 3.times.map { gets.chomp }
p s1
p s2
p s3
s1, s2, s3 = readlines.map(&:chomp)
p s1
p s2
p s3
結果
"Ruby"
"Python"
"Java"

1行に複数(半角スペース区切り) & 複数行

数値

入力値
1 2 3
4 5 6
m_arr = readlines.map { |i| i.split.map(&:to_i) }
p m_arr
結果
[[1, 2, 3], [4, 5, 6]]

多次元配列を一次元配列にする場合

arr = m_arr.flatten
p arr
結果
[1, 2, 3, 4, 5, 6]

変数に格納する場合

n1, n2, n3, n4, n5, n6 = readlines.map(&:split).flatten
p n1
p n2
p n3
p n4
p n5
p n6
結果
1
2
3
4
5
6

文字列

入力値
a b c
d e f
m_arr = 2.times.map { gets.split }
p m_arr
m_arr = readlines.map(&:split)
p m_arr
結果
[["a", "b", "c"], ["d", "e", "f"]]

多次元配列を一次元配列にする場合

arr = m_arr.flatten
p arr
結果
["a", "b", "c", "d", "e", "f"]

変数に格納する場合

s1, s2, s3, s4, s5, s6 = readlines.map(&:split).flatten
puts s1
puts s2
puts s3
puts s4
puts s5
puts s6
結果
a
b
c
d
e
f

おまけ

入力値
a b
c d
e f
m_arr = readlines.map(&:split)

puts 'arr[0]'
puts '------'
m_arr.each { |arr| p arr[0] }
puts ''

puts 'arr[1]'
puts '------'
m_arr.each { |arr| p arr[1] }
結果
arr[0]
------
"a"
"c"
"e"

arr[1]
------
"b"
"d"
"f"

その他(知っておくと役立つメソッド)

※ 競プロ系の学習をしているので、ついでに役立ちそうなメソッドをメモ書きしています

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