1
0

【Ruby】問題集解答 Part1(paizaラーニング)

Last updated at Posted at 2024-03-03

N行のデータの入力 (paizaランク D 相当)

自分の解答

まず空の配列を用意し、その中に受け取った数値の個数分だけ値を格納し、最後にputsする。
勉強のために、forwhileの2つの方法で書いた。

practice_01.rb
times = gets.to_i

array = []

# forの場合
# for i in 1..times
#     array << gets
# end

# whileの場合
num = 1
while num <= times
  array << gets
  num += 1
end

puts array

ChatGPTの解答

以下は、Rubyで提供された条件に基づいて問題を解決するためのサンプルコードです。このコードは、すべての入力を受け取った後にまとめて出力します。

ruby
# Nの値を取得
n = gets.to_i

# N行分の文字列を受け取り、配列に格納
input_strings = []
n.times { input_strings << gets.chomp }

# 入力を受け取った後に出力
input_strings.each do |str|
  # ここに各文字列に対する処理を記述
  # 例えば、文字列をそのまま出力する場合は以下のようになります
  puts str
end

このコードでは、まず最初に行数 N を取得し、その後 N 行分の文字列を受け取ります。最後に、各文字列に対する処理を行いつつ、全体を一括して出力します。各文字列に対する具体的な処理は必要に応じて変更してください。

学び

timesメソッドを使えばより簡潔に書ける。

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