2011-10-30 141 views
1

我有兩個文件:紅寶石1.8.7未定義的局部變量

confidant.rb:

# 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 

中的錯誤信息運行紅寶石confidant.rb結果:12:未定義的局部變量或方法'code_words'爲 main:Object(NameError)

我必須以某種方式限定code_words嗎?代碼是來自_why的尖銳指南的稍微改編的例子。

+2

感謝這兩個答案。 – lowerkey

+1

如果你要在最後換行,你應該使用'puts'而不是'print'。 –

回答

6

是的,從其他文件的本地變量沒有拉。你可以通過使code_words成一個全局變量(如解決這個問題,CODE_WORDS ),然後相應地更改它在confidant.rb

+0

夠好,因爲這就是一個例子。 – lowerkey

+0

'CODE_WORDS'將是一個全球常數。如果你想要一個全局變量,所以你可以稍後修改它,把它叫做'$ code_words'。 –

2

你應該在這裏使用實例變量(與@號)

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

通常我會和你的答案一起去,但在這個例子中,我認爲這會過度(這將與分析水平進入樣本,但嘿,我正在學習) – lowerkey

相關問題