require_relative不拉变量?

require_relative doesn't pull the variables?

一直在从 _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"
}

在我的另一个文件中,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 可以工作,因为如果我 运行 pluto.rb 没有散列部分(只输入 "Hello World"),Hello World 就会打印出来!

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

module World
  CODE_WORDS = { ... }
end

并在 pluto.rb 中:

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