ruby 1.8.7 undefined局部变量

时间:2011-10-30 00:55:53

标签: ruby

我有两个文件:

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

# 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

运行ruby confidant.rb会出现错误消息:

  

confidant.rb:12:未定义的局部变量或方法'code_words'   main:Object(NameError)

我是否必须以某种方式限定code_words?该代码是_why的尖锐指南中稍微适应的例子。

2 个答案:

答案 0 :(得分:6)

是的,其他文件中的局部变量不会被拉入。您可以通过将code_words转换为全局变量(例如CODE_WORDS)然后在confidant.rb中相应地更改它来解决此问题。 }

答案 1 :(得分:2)

您应该在此处使用实例变量(使用@符号)

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