Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.ruby > #2185

Re: Using variables in modules

From Brian Candler <b.candler@pobox.com>
Newsgroups comp.lang.ruby
Subject Re: Using variables in modules
Date 2011-04-03 02:55 -0500
Organization Service de news de lacave.net
Message-ID <42edceffd89bb95234be06fa427ccd18@ruby-forum.com> (permalink)
References <1301790250.3173.40.camel@AMD64X2.fritz.box>

Show all headers | View raw


Stefan Salewski wrote in post #990601:
> I have a module named Config with a configuration hash, with
> predefined colors. I access that hash from other modules. That hash
> should have default values, but it should be possible to redefine it.

If you want to do this with a constant then you probably want 
Hash#replace:

Config::Colors = {:red => 1, :blue => 2}
Config::Colors.replace({:red => 3, :blue => 4})

You'll get no warning because the constant still points to the same 
object, you've just mutated that object. But as others have said, a 
class instance variable is probably cleaner.

Hash#merge is useful too when you have defaults, so unspecified keys 
retain their default values:

def configure(settings)
  Config::Colors.replace(Config::Defaults.merge(settings))
end

-- 
Posted via http://www.ruby-forum.com/.

Back to comp.lang.ruby | Previous | NextPrevious in thread | Next in thread | Find similar | Unroll thread


Thread

Using variables in modules Stefan Salewski <mail@ssalewski.de> - 2011-04-02 19:30 -0500
  Re: Using variables in modules Stefan Salewski <mail@ssalewski.de> - 2011-04-02 19:57 -0500
    Re: Using variables in modules Stefano Crocco <stefano.crocco@alice.it> - 2011-04-03 01:39 -0500
  Re: Using variables in modules Brian Candler <b.candler@pobox.com> - 2011-04-03 02:55 -0500
  Re: Using variables in modules spiralofhope <spiralofhope_rubyml@lavabit.com> - 2011-04-03 12:37 -0500
    Re: Using variables in modules Stefan Salewski <mail@ssalewski.de> - 2011-04-03 15:29 -0500
    Re: Using variables in modules Brian Candler <b.candler@pobox.com> - 2011-04-03 15:30 -0500

csiph-web