How to step through a loop with pry and view the value of an iterator?

自古美人都是妖i 提交于 2019-12-08 05:43:37

问题


I inserted binding.pry into my Ruby program and am trying to view the value of an iterator at each iteration of my loop:

require 'pry'

def longest_palindrome s
  max_palindrome_len = 0
  for i in (0..s.length)
    binding.pry
    for j in (i..s.length)
      binding.pry
      substr = s[i..j]
      if substr == substr.reverse && substr.length > max_palindrome_len
        max_palindrome_len = substr.length
      end
    end
  end
  return max_palindrome_len
end

longest_palindrome "racer"

I want to view the values for i and j at each iteration in the loop.

I'm sure I'm just missing something here, but I haven't been able to figure out what to do from the documentation.


回答1:


You can type p i and p j to manually inspect them.

That'd make me crazy though, so I'd insert puts i and puts j temporarily.

Don't use for loops with Ruby. Instead we use each or upto, downto or times, depending on our purpose. Also, explicit return statements aren't needed at the end of a method unless you are forcing the code to exit early.

I'd write your code something like:

require 'pry'

def longest_palindrome(s)
  max_palindrome_len = 0

  s.length.times do |i|
    binding.pry
    i.upto(s.length) do |j|
      binding.pry
      substr = s[i..j]
      if substr == substr.reverse && substr.length > max_palindrome_len
        max_palindrome_len = substr.length
      end
    end
  end

  max_palindrome_len
end

longest_palindrome "racer"


来源:https://stackoverflow.com/questions/35323710/how-to-step-through-a-loop-with-pry-and-view-the-value-of-an-iterator

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!