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 基礎 #1

0
Posted at

📝 入力処理の基本パターン

改行区切りの入力→複数回に分て入力される

# 2つの整数を改行区切りで受け取る
x = gets.to_i
y = gets.to_i
puts x * y

スペース区切りの入力→一度に複数の値が入力される

# 2つの整数をスペース区切りで受け取る
x, y = gets.split.map(&:to_i)
puts x + y

複数行の入力

# 5行の整数を配列で受け取り最小値を返す
numbers = 5.times.map { gets.to_i }
puts numbers.min

🔤 文字列処理のコツ

文字列比較

chompは改行を除去する

# 改行を除去してから比較
# 文字列が同一かを調べる
a = gets.chomp
b = gets.chomp

if a == b
  puts "OK"
else
  puts "NG"
end

# 短縮版
puts (gets.chomp == gets.chomp ? "OK" : "NG")

文字列結合

# 2つの文字列を@で結合
puts [gets.chomp, gets.chomp].join("@")

# または
s = gets.chomp
t = gets.chomp
puts s + "@" + t

🧮 数値計算の基本

四則演算と剰余

# 商と余りを出力
puts "#{a / b} #{a % b}"

# 2乗の計算
puts ((a + b) * c) ** 2

変数の更新

# ある数字a, b, cが入力された時、それぞれをnに代入していき結果を出力
n = 0
n += a
n *= b
n %= c
puts n

🔄 ループ処理

基本的なwhile文

# 1からNまで出力
n = gets.to_i
i = 1
while i <= n
  puts i
  i += 1
end

よりRubyらしい書き方

# timesメソッドを使用
n = gets.to_i
n.times do |i|
  puts i + 1
end

# eachメソッドを使用
n = gets.to_i
(1..n).each { |i| puts i }

条件分岐のループ

n = gets.to_i

(1..n).each do |i|
  if i % 20 == 0
    puts "〇〇△△"
  elsif i % 4 == 0
    puts "〇〇"
  elsif i % 5 == 0
    puts "△△"
  else
    puts i
  end
end

🎯 条件分岐のテクニック

三項演算子の活用

# 条件 ? 真の場合 : 偽の場合
a, b, c = gets.split.map(&:to_i)
puts a * b <= c ? "YES" : "NO"

比較演算子の使い方

# 不等号は=の左
n <= 100  # Nが100以下の場合
n >= 100  # Nが100以上の場合

📊 配列操作の基本

split.map(&:to_i)

・split:文字列を空白文字で区切って配列にする
・.map(何か):"何か"の部分が適用された新しい配列を作る
・.map(&:to_i):配列の各要素を整数に変換する

split

"10 20 30".split
# => ["10", "20", "30"]
  • 文字列を空白区切りで分割して配列にする
  • デフォルトはスペースやタブが区切りになる

map(&:to_i)

["10", "20", "30"].map(&:to_i)
# => [10, 20, 30]
  • この場合は「文字列を整数に変換する処理」を行っている
  • 「配列の要素一つひとつに to_i を適用して配列に戻す」という意味

実際の入力処理で使うと…

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

入力例:

10 20 30

処理の流れ:

  1. gets"10 20 30\n"
  2. split["10", "20", "30"]
  3. map(&:to_i)[10, 20, 30]

結果:

numbers # => [10, 20, 30]

🔧 文字列と演算子の組み合わせ

掛け算(文字列を繰り返し出力)

n = 4
puts "*" * n  # => ****
puts "ab" * 3  # => ababab

足し算(文字列を連結)

puts "Hello" + " " + "World"  # => Hello World

引き算(部分的に文字列を削除)

puts "HelloWorld" - "World"  # => Hello
puts "abcabc" - "a"  # => bcbc

割り算(考えなくてよい)

# 文字列に対する / は定義されていない(エラーになる)
"abc" / 2  # => NoMethodError

💡 重要なポイント

入力処理の注意点

  • getsは末尾に改行文字\nを含む
  • 文字列比較時は.chompで改行を除去
  • putsは改行付き、printは改行なしで出力

変数命名の慣習

  • 小文字始まり = 変数
  • 大文字始まり = 定数

文字列補間

# #{...}で計算結果を文字列に埋め込み
puts "#{x - y} #{x * y}"
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?