请有人向我解释,为什么不初始化first_idx和last_idx会导致代码无法运行?
当我运行它时,我得到这个错误"未定义的局部变量或方法last_idx".我知道建议是始终初始化变量,但我不明白为什么.毕竟first_idx和last_idx总是会在循环中得到一个值,因为参数lette r总是出现在字符串中(在这个特殊的问题中).
我真的很感激一些(简单的)洞察力.谢谢!
PS,我也知道在Ruby中使用#index和#rindex很容易解决这个问题,但我不允许用简单的方法解决它.
def find_for_letter(string, letter)
first_idx = nil
0.upto(string.length - 1) do |idx1|
if string[idx1] == letter
first_idx = idx1
break
end
end
last_idx = nil
(string.length - 1).downto(0) do |idx2|
if string[idx2] == letter
last_idx = idx2
break
end
end
if last_idx == first_idx
return [first_idx]
else
return [first_idx, last_idx]
end
end
def first_last_indices(word)
h = {}
word.chars.each do |char|
h[char] = find_for_letter(word, char)
end
h
end
Run Code Online (Sandbox Code Playgroud)