2016-05-12 23 views
-2

从_why的书中学习Ruby,我尝试重新创建他的代码,但它不起作用。require_relative不拉动变量?

我有一个world.rb文件;

puts "Hello World" 

Put_the_kabosh_on = "Put the kabosh on" 
code_words = { 
    starmonkeys: "Phil and Pete, thouse prickly chancellors of the New Reich", 
    catapult: "Chunky go-go", 
    firebomb: "Heat-Assisted Living", 
    Nigeria: "Ny and Jerry's Dry Cleaning (with Donuts)", 
    Put_the_kabosh_on: "Put the cable box on" 
} 

而在我的其他文件,pluto.rb;

require_relative "world" 

puts "Hello Pluto" 
puts code_words[:starmonkeys] 
puts code_words[:catapult] 
puts code_words[:firebomb] 
puts code_words[:Nigeria] 
puts code_words[:Put_the_kabosh_on] 

我知道我的require_relative的作品,因为如果我不散列部(只是把"Hello World")运行pluto.rb,您好世界获取打印!

+0

如果你expectecting的code_words局部变量pluto.rb存在,那么它不会。这是要求(_relative)工作的方式 –

+0

您的问题是什么? – sawa

+0

在一个Rails应用程序中,你应该把它们放在一个YAML文件中。看看http://guides.rubyonrails.org/i18n.html – Stefan

回答

2

局部变量是本地变量:它们不能在require之间生存。全局变量($code_words),常量(CODE_WORDS)和实例变量(@code_words)都可以。类变量(@@code_words)也可以,但会收到警告。其中,常数是最不臭的;但它会更好,如果你把它们放在一个模块中它们的命名应该:

module World 
    CODE_WORDS = { ... } 
end 

pluto.rb

require_relative "world" 
puts World::CODE_WORDS[...]