1
votes

I have two files:

# wordlist.rb
code_words = {
    'computer' => 'devil worshipping device',
    'penny' => 'pretty',
    'decoration' => 'girlandes, green light bulbs, skeletons',
    'pets' => 'captured souls'
}

and

# confidant.rb
require 'wordlist'

# Get string and swap in code words
print 'Say your piece: 
'

idea = gets
code_words.each do |original, translated|
    idea.gsub! original, translated
end

# Save the translated idea to a new file
print 'File encoded. Please enter a name for your piece: 
'

piece_name = gets.strip
File::open 'piece-' + piece_name + '.txt', 'w' do |f|
    f << idea
end

running ruby confidant.rb results in an error message:

confidant.rb:12: undefined local variable or method 'code_words' for main:Object (NameError)

Do I have to qualify code_words somehow? The code is a slightly adapted example from _why's poignant guide.

2
Thanks to the both for the answers. - lowerkey
You should use puts instead of print if you are going to have a newline at the end. - David Grayson

2 Answers

6
votes

Yes, local variables from other files aren't pulled in. You could remedy this by making code_words into a global variable (e.g., CODE_WORDS) and then changing it accordingly in confidant.rb

2
votes

You should use instance variable here (with @ sign)

# wordlist.rb
@code_words = {
    'computer' => 'devil worshipping device',
    'penny' => 'pretty',
    'decoration' => 'girlandes, green light bulbs, skeletons',
    'pets' => 'captured souls'
}