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.
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