1

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 require_relativeworks, because if I run pluto.rb without the hash part (just puts "Hello World"), Hello World gets printed!

3
  • If you're expectecting the code_words local variable to exist in pluto.rb, then it won't. This is the way require(_relative) works Commented May 12, 2016 at 8:56
  • What is your question? Commented May 12, 2016 at 8:59
  • Within a Rails app, you should put these in a YAML file. Take a look at guides.rubyonrails.org/i18n.html Commented May 12, 2016 at 9:53

1 Answer 1

5

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 = { ... } end 

and in pluto.rb:

require_relative "world" puts World::CODE_WORDS[...] 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.