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?

More than 3 years have passed since last update.

Rubyでの標準入力のあれこれ

Last updated at Posted at 2021-02-05

#一行の要素を取得
##文字列

string = gets.chomp

#標準入力
Spring

#出力
p string
=> "Spring"

##数値

number = gets.chomp.to_i

#標準入力
100

#出力
p number
=> 100

#一行の複数要素を取得
##文字列

line = gets.chomp.split

#標準入力
Spring Summer Autumn

#出力
p line
=> ["Spring", "Summer", "Autumn"]

##数値

line = gets.chomp.split.map(&:to_i)

#標準入力
1 2 3

#出力
p line
=> [1, 2, 3]

#一行の文字列を一文字ずつ取得

line = gets.chomp.split("")

#標準入力
SPRING

#出力
p line
=> ["S", "P", "R", "I", "N", "G"]

#複数行の要素を取得
##文字列

array = []
while string = gets
  array << string.chomp
end

#標準入力
Spring
Summer
Autumn

#出力
p lines
=>  ["Spring", "Summer", "Autumn"]

#この書き方でも同じ結果になる
lines = readlines
i = 0
while i < lines.length
  lines[i] = lines[i].chomp
  i += 1
end

p lines
=>  ["Spring", "Summer", "Autumn"]

#この書き方でも同じ結果になる
lines = readlines.map(&:chomp)

p lines
=>  ["Spring", "Summer", "Autumn"]

##数値

array = []
while number = gets
  array << number.chomp.to_i
end

#標準入力
1
2
3

#出力
p lines
=>  [1, 2, 3]


#この書き方でも同じ結果になる
lines = readlines.map(&:to_i)

p lines
=>  [1, 2, 3]

#複数行の複数要素を取得
##文字列

array = []
while string = gets
  array << string.chomp.split
end

#標準入力
Spring Summer
Autumn Winter

#出力
p array
=>  [["Spring", "Summer"], ["Autumn", "Winter"]]

#この書き方でも同じ結果になる
lines = readlines
i = 0
while i < lines.length
  lines[i] = lines[i].chomp.split
  i += 1
end

#この書き方でも同じ結果になる
lines = readlines.map{|line| line.split}

p lines
=>  [["Spring", "Summer"], ["Autumn", "Winter"]]

##数値

array = []
while string = gets
  array << string.chomp.split.map(&:to_i)
end

#標準入力
1 2
3 4

#出力
p array
=>  [[1, 2], [3, 4]]

#この書き方でも同じ結果になる
lines = readlines.map{|line| line.split.map(&:to_i)}

p lines
=>  [[1, 2], [3, 4]]
0
0
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
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?