-1

Have an external file, wordlist.rb, that contains

code_words = { 'a' => 'is a', 'b' => 'is b' }

This file is stored in the same directory that contains my code require 'wordlist'

code_word.each do | mykey, mysentence | puts mykey + "=> " mysentence end

when I run this code, I get the following message

<main>': undefined local variable or method code_words' for main:Object (NameError)

thanks for the help

4

2 回答 2

2

You should have a global variable(i.e. starting with a $) to be able to access it from a file that you require.

于 2013-03-10T16:23:41.607 回答
2

是的,它是一个局部变量。局部变量在定义它们的范围内是局部的。这就是它们被称为局部变量的原因。您不能访问另一个作用域的局部变量,这就是局部变量的全部意义所在。

如果您希望变量在全局范围内,则需要使用全局变量。

但是,在这种情况下,看起来您实际上想要一个全局常量,而不是变量:

CODE_WORDS = { 'a' => 'is a', 'b' => 'is b' }

puts CODE_WORDS.map {|mykey, mysentence| "#{mykey} => #{mysentence}" }.join("\n")
于 2013-03-10T20:42:38.560 回答