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?

Ruby プログラミング問題攻略Tips 基礎 #2

0
Last updated at Posted at 2025-09-20

to_a

・『to』は『〜にする』
・『a』は配列(array)

putsに配列を渡すと。。。

・配列の中身を展開し、各要素に対して改行付きで出力する

arr = [1, 2, 3]
puts arr
#出力結果
1
2
3

putsは文字列に変換して出力する

・内部では数値を整数として扱うの計算が可能

a = 10
b = 5
puts a + b 
puts (a + b).class
15
Integer

printとputsの違い

・putsは出力した後に、自動で改行を入れる
・printはオブジェクトをそのまま文字列化して出力する

puts "hello"
puts "world"

print "hello"
print "world"
# 出力結果
hello
world
helloworld

※putsは自動で改行、printは改行しない

arr = [1, 2, 3]

puts arr
print arr
# 出力結果
1
2
3
[1, 2, 3]

※putsは各要素を改行しながら出力する。
※printは配列そのものを文字列化して出力する

入力が1行で1度だけか複数行で何度もかで、getsの使い方を分ける

・1行で複数個受け取るパターン

# 入力される値
1 2 3 4 5
# 1行でまとめて受け取る
num = gets.split.map(&:to_i).join(" ")

puts num
# 出力結果
1 2 3 4 5

・複数行で何個も受け取るパターン

# 入力される値
1
2
3
4
5
# 5行分の入力を配列に格納
num = []
5.times do
  num << gets.to_i
end

puts num
# 出力結果
1
2
3
4
5

num = gets.split.map(&:to_i).join(" ")

・gets.split.map(&:to_i) → [1, 2, 3, 4, 5] (配列)
・.join(" ") → "1 2 3 4 5" (文字列)
・puts num → "1 2 3 4 5" を1行で出力
・この場合、num は文字列だから『1行』になる

num = gets.split.map(&:to_i)

・gets.split.map(&:to_i) → [1, 2, 3, 4, 5] (配列)
・num は 配列のまま
・puts num → 配列を渡すと要素ごとに改行して出力

# 出力結果
1
2
3
4
5

・この場合、num は配列だから『要素ごとに改行』になる

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?