我正在学习 Ruby 并通过编写凯撒密码进行练习。到目前为止,这是我的代码:
print "Enter rotation: "
rotation = gets.chomp
print "Enter string to encrypt: "
string = gets.chomp
def encrypt
keys = (' '..'z').to_a
values = (' '..'z').to_a.rotate(rotation)
hash = Hash[keys.zip(values)]
chars = string.split('')
encrypted_chars = chars.collect { |char| hash[char] }
encryptd_string = encrypted_chars.join
end
puts "Encrypted string: " + encrypt
这是说我无法访问 encrypt
方法中的 rotation
变量。 NameError: main:Object 的未定义局部变量或方法“旋转”
。
据我所知,rotation
是一个具有外部作用域的局部变量,应该可以在 encrypt
方法内部访问。显然这种推理有问题,那么有人可以解释一下哪里出了问题吗?
最佳答案
这是 Ruby accessing outer variables in nested function 的副本.
您可以通过调用 @rotation
使其成为包含对象的实例变量,但为什么不直接将 string
和 rotation
传递给加密
方法?
关于ruby - 您可以在方法内部访问具有外部作用域的 Ruby 变量吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23557993/