我正在学习 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内部的变量encrypt。NameError: undefined local variable or method 'rotation' for main:Object.
据我所知,rotation是一个具有外部作用域的局部变量,应该可以在encrypt方法内部访问。显然,这种推理有问题,所以有人可以解释一下出了什么问题吗?
您可以通过调用 it 使其成为包含对象上的实例变量@rotation,但为什么不直接将string和传递rotation到encrypt方法中呢?
| 归档时间: |
|
| 查看次数: |
4192 次 |
| 最近记录: |