0

I am using one file in the initializers directory to declare constants for use in different parts of the application.

FIRST_STR = "First Name"
LAST_STR = "Last Name"
new_user_hash = Hash.new
new_user_hash[ "first" ] = FIRST_STR
new_user_hash[ "last" ] =  LAST_STR

I have no problem using FIRST_STR and LAST_STR in different parts of the application, but when I try to use new_user_hash, I get the following error message:

undefined local variable or method `new_user_hash' for #<#:0x007f8da5752da0>

Is it not possible to define/declare a hash in one file and use it in another?

1
  • Where are you trying to use new_user_hash? It can't be accessed outside of that file since it's a local variable. Commented May 12, 2012 at 16:25

2 Answers 2

7

I think you may be running into scoping—new_user_hash is a local and may not be available to the rest of the application. If you make it a global (by calling it $new_user_hash) it will be available. In the case of FIRST_STR and LAST_STR, they are constants which are effectively globals.

Update your code to be either:

$new_user_hash = { "first" => FIRST_STR, "last" => LAST_STR }

or

NEW_USER_HASH  = { "first" => FIRST_STR, "last" => LAST_STR }

And you will be able to access $new_user_hash or NEW_USER_HASH from the other parts of your application.

Another strategy is to define a module:

module MyAppConfig
  NEW_USER_HASH = { "first" => FIRST_STR, "last" => LAST_STR } 
end

Then elsewhere you can access it by prefixing it with the module name:

MyAppConfig::NEW_USER_HASH["first"]

This is a more accepted approach since it doesn't create more global variables.

Sign up to request clarification or add additional context in comments.

5 Comments

MyAppConfig probably makes more sense as a module, since it's not meant to be new-ed and is merely a container for encapsulating constants.
That is a great point Andrew. Thanks, I'll update my answer.
Thanks for all the suggestions. I will try some stuff and post what works. Yes, it's a scoping issue. When I moved the Hash declaration to the file I was using it in, it worked fine.
Is the module approach to help avoid a name conflict only, or are there other advantages to using the module approach?
Andrew's suggestion is a good one: since there is no implementation (i.e. no state) there is no need to make it a class -- you'd never instantiate it (call new) and it really has no behavior of its own, it's just there to namespace the data. Does this make sense?
0

You should use a config management gem: https://www.ruby-toolbox.com/categories/Configuration_Management

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.