4

Given the following code:

require 'pry-byebug'

10.times.with_index do |i|
  binding.pry
  puts i
end

I'd like to "loop until i == 5 then break" while inside pry-byebug. From running it help break it seems like you can identify breakpoints by "breakpoint #" or "line #". It also seems like you can use conditions, however I'm not getting it to work:

Trying to set breakpoint on line #:

$  ruby foo.rb

From: /Users/max/Dropbox/work/tmp/pry_debug/foo.rb @ line 5 :

    1: require 'pry-byebug'
    2:
    3: 10.times.with_index do |i|
    4:   binding.pry
 => 5:   puts i
    6: end

[1] pry(main)> break foo.rb:5 if i == 5

  Breakpoint 1: /Users/max/Dropbox/work/tmp/pry_debug/foo.rb @ 5 (Enabled) Condition: i == 5


    2:
    3: 10.times.with_index do |i|
    4:   binding.pry
 => 5:   puts i
    6: end


[2] pry(main)> continue
0

From: /Users/max/Dropbox/work/tmp/pry_debug/foo.rb @ line 5 :

    1: require 'pry-byebug'
    2:
    3: 10.times.with_index do |i|
    4:   binding.pry
 => 5:   puts i
    6: end

[2] pry(main)> i
=> 1

First setting breakpoint then putting condition on break point:

➜  ~/D/w/t/pry_debug  ruby foo.rb

From: /Users/max/Dropbox/work/tmp/pry_debug/foo.rb @ line 5 :

    1: require 'pry-byebug'
    2:
    3: 10.times.with_index do |i|
    4:   binding.pry
 => 5:   puts i
    6: end

[1] pry(main)> break foo.rb:15

  Breakpoint 1: /Users/max/Dropbox/work/tmp/pry_debug/foo.rb @ 15 (Enabled)



[2] pry(main)> break --condition 1 i == 5
[3] pry(main)> c
0

From: /Users/max/Dropbox/work/tmp/pry_debug/foo.rb @ line 5 :

    1: require 'pry-byebug'
    2:
    3: 10.times.with_index do |i|
    4:   binding.pry
 => 5:   puts i
    6: end

[3] pry(main)> i
=> 1

As you can see, in both cases pry-byebug doesn't respect the condition because it stops too soon. How do I get it to work?

4

2 回答 2

10

我认为一个简单的方法是在你的代码中做到这一点:

require 'pry-byebug'

10.times.with_index do |i|
  binding.pry if i == 5
  puts i
end

或者,如果您想在异常处停止,您可以执行以下操作:

require 'pry-byebug'

10.times.with_index do |i|
  puts i rescue binding.pry # if the puts command throws an exception, you'll be taken to pry
end
于 2017-01-04T23:26:49.653 回答
1

从循环内部移除binding.pry并将其放在之前10.times

binding.pry
10.times.with_index do |i|

然后运行代码。当它到达断点时,然后使用您想要的条件设置一个新断点和continue.

回到你的实际代码。不要这样做:

10.times.with_index do |i|

相反,这将做几乎相同的事情,但更简单:

10.times do |i|

这是 Ruby 正在做的事情:

>> 2.times.with_index.to_a
[
  [0] [
    [0] 0,
    [1] 0
  ],
  [1] [
    [0] 1,
    [1] 1
  ]
]

对比

>> 2.times.to_a
[
  [0] 0,
  [1] 1
]

首先是传入 , 等数组[0,0][1,1]因此为了正确起见,您的块参数需要类似于:

10.times.with_index do |i, j|

第二个只传递当前的“次”值,从而产生更简单的代码。

于 2017-01-05T17:17:10.213 回答