Mc-Ac Mc-Ac - 5 months ago 5
Ruby Question

require_relative doesn't pull the variables?

Been learning Ruby from _why's book and I tried to recreate his code, but it doesn't work.

I have a world.rb file ;

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"

And in my other file, 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]

I know my
works, because if I run pluto.rb without the hash part (just puts
"Hello World"
), Hello World gets printed!


Local variables are local: they don't survive across a require. Global variables ($code_words), constants (CODE_WORDS) and instance variables (@code_words) do. Class variables (@@code_words) do as well, but you'll get a warning. Of these, constants are the least smelly; but it would be better if you put them in a module to namespace them:

module World
  CODE_WORDS = { ... }

and in pluto.rb:

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