require_relative 不拉变量?

Mc-*_*-Ac 1 ruby variables ruby-on-rails require

我一直在从 _why 的书中学习 Ruby,我尝试重新创建他的代码,但它不起作用。

我有一个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"
}
Run Code Online (Sandbox Code Playgroud)

在我的另一个文件中, 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]
Run Code Online (Sandbox Code Playgroud)

我知道我的require_relative作品,因为如果我在没有哈希部分的情况下运行 pluto.rb (只是 put "Hello World"),Hello World 就会被打印!

Ama*_*dan 5

局部变量是局部的:它们不能在require. 全局变量 ( $code_words)、常量 ( CODE_WORDS) 和实例变量 ( @code_words) 都可以。类变量 ( @@code_words) 也可以,但您会收到警告。其中,常量是最不臭的;但如果将它们放在一个模块中以命名它们会更好:

module World
  CODE_WORDS = { ... }
end
Run Code Online (Sandbox Code Playgroud)

并在pluto.rb

require_relative "world"
puts World::CODE_WORDS[...]
Run Code Online (Sandbox Code Playgroud)