您可以在方法内部访问具有外部作用域的 Ruby 变量吗?

Ada*_*ner 5 ruby scope

我正在学习 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
Run Code Online (Sandbox Code Playgroud)

这是说我无权访问方法rotation内部的变量encryptNameError: undefined local variable or method 'rotation' for main:Object.

据我所知,rotation是一个具有外部作用域的局部变量,应该可以在encrypt方法内部访问。显然,这种推理有问题,所以有人可以解释一下出了什么问题吗?

Buc*_*yle 5

这是Ruby 访问嵌套函数中的外部变量的重复。

您可以通过调用 it 使其成为包含对象上的实例变量@rotation,但为什么不直接将string和传递rotationencrypt方法中呢?