在这个凯撒密码中,"print i[-1]" 是如何从 z 换到 a 的?
How did "print i[-1]" wrap from z to a in this caesar cipher code?
正如标题所说,为什么我们在这段代码中使用"print i[-1]"?
def caesar_cipher (string, number)
string.scan (/./) do |i|
if ("a".."z").include? (i.downcase) # Identify letters only.
number.times {i = i.next}
end
print i[-1] # Wrap from z to a.
end
end
caesar_cipher("Testing abzxc.", 5)
我理解除该特定行之外的所有代码。 ruby 是如何将 Z 包装成 A 的?我的意思是看这段代码:
test1 = "z"
puts test1[-1]
# result is Z not A
我原以为结果是 A,但结果是 Z。有人可以解释一下我在这里遗漏了什么吗?
参见String#[]
:
test1[-1]
returns 字符串的最后一个字母。由于字符串"z"
的最后一个字母是"z"
,它returns它。
如果输入是 "z"
,caesar_cipher("z", 5)
将调用 i = i.next
5 次,这会将 i
移动到后面的第 5 个元素。
i = "z"
i = i.next # aa
i = i.next # ab
i = i.next # ac
i = i.next # ad
i = i.next # ae
现在,i[-1]
将从结果中提取最后一个字符,并丢弃前导进位 a
。
正如标题所说,为什么我们在这段代码中使用"print i[-1]"?
def caesar_cipher (string, number)
string.scan (/./) do |i|
if ("a".."z").include? (i.downcase) # Identify letters only.
number.times {i = i.next}
end
print i[-1] # Wrap from z to a.
end
end
caesar_cipher("Testing abzxc.", 5)
我理解除该特定行之外的所有代码。 ruby 是如何将 Z 包装成 A 的?我的意思是看这段代码:
test1 = "z"
puts test1[-1]
# result is Z not A
我原以为结果是 A,但结果是 Z。有人可以解释一下我在这里遗漏了什么吗?
参见String#[]
:
test1[-1]
returns 字符串的最后一个字母。由于字符串"z"
的最后一个字母是"z"
,它returns它。
如果输入是 "z"
,caesar_cipher("z", 5)
将调用 i = i.next
5 次,这会将 i
移动到后面的第 5 个元素。
i = "z"
i = i.next # aa
i = i.next # ab
i = i.next # ac
i = i.next # ad
i = i.next # ae
现在,i[-1]
将从结果中提取最后一个字符,并丢弃前导进位 a
。