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 pを使ったコード検証(デバック)

Posted at

###pを使ったコードの検証方法
 想定した処理がどこまで正しく行われているか?デバックして状況確認をする

使えそうなシーン
 ・ エラーが起こったとき
 ・ 今この変数は文字列?数値?配列?
 ・ ifで正しく条件分岐されてるのか?
 ・ 他人のコードの処理の流れを追いながら理解したい

方法
 「p」を処理ごとに分かりやすく文字/数値で入れる


例① 他人のコードの処理の流れを追いながら理解したい

.rb
p "a:"
seats_and_groups = gets.split(/\s/)
p "b:"
empty_seat = [*1..(seats_and_groups[0].to_i)]
p "c:"
seats_count = empty_seat.count
p "d:"
number_of_visitors = seats_and_groups[1].to_i
p "e:"
[*1..number_of_visitors].each do
  p "f:"
  used_seats = gets.split(/\s/)
  p "g:"
  users = used_seats[0].to_i
  p "h:"
  seating_number = used_seats[1].to_i
  p "i:"
  fill_last_number = ((seating_number + users) - 1)
    続

出力 (入力1回目[6 3]/2回目[2 3]での、実行された処理の違いが分かりやすい)

"a:"
6 3
"b:"
"c:"
"d:"
"e:"
"f:"
2 3
"g:"
"h:"
"i:"

例② 今この変数は文字列?数値?配列?

.rb
  if next_seat_candidate.count == next_seat_candidate.uniq.count
    p "1:"
    p empty_seat
    if ((seating_number + users) - 1) > seats_count
      empty_seat = empty_seat - [*1..fill_last_number]
      empty_seat = empty_seat - [*seating_number..seats_count]
    else
      empty_seat = empty_seat - [*seating_number..fill_last_number]
      p "2:"
      p empty_seat
    end

出力(変数/配列の状況の変化がわかる)

"1:"
[1, 2, 3, 4, 5, 6]
"n"
"p"
"2:"
[1, 2, 5, 6]
"f:"

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?