【问题标题】:ruby 1.8.7 undefined local variableruby 1.8.7 未定义的局部变量
【发布时间】:2011-10-30 00:55:53
【问题描述】:

我有两个文件:

# 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' 主:对象(名称错误)

我必须以某种方式限定 code_words 吗?该代码是 _why's poignant guide 中的一个略微改编的示例。

【问题讨论】:

  • 感谢两位的回答。
  • 如果你要在末尾换行,你应该使用puts 而不是print

标签: ruby


【解决方案1】:

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

【讨论】:

  • 很好,因为这是一个例子。
  • CODE_WORDS 将是一个全局常量。如果您想要一个全局变量以便以后修改它,请调用它$code_words
【解决方案2】:

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

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

【讨论】:

  • 通常我会接受你的回答,但在这个例子中,我认为这有点矫枉过正(这将与样本中的分析水平有关,但是嘿,我正在学习)
猜你喜欢
  • 2012-03-29
  • 2013-04-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多