Adam Zerner Adam Zerner - 5 months ago 23x
Ruby Question

Can you access Ruby variables with outer scope inside of methods?

I'm learning Ruby and practicing by writing a Caesar cipher. Here's my code so far:

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[]
chars = string.split('')
encrypted_chars = chars.collect { |char| hash[char] }
encryptd_string = encrypted_chars.join

puts "Encrypted string: " + encrypt

It's saying that I don't have access to the
variable inside of the
NameError: undefined local variable or method 'rotation' for main:Object

From what I understand,
is a local variable with outer scope, and should be accessible inside of the
method. Obviously something is wrong with that reasoning, so could someone explain what's wrong?


This is a duplicate of Ruby accessing outer variables in nested function.

You could make it an instance variable on the containing object by calling it @rotation, but why not just pass string and rotation into the encrypt method?