Use class constant as Ruby hash key -


i know can use class hash key, practice? there drawbacks in terms of performance or testing?

{   someclassa: 'hash value',   anotherclass: 'hash value' } 

{   someclassa: 'hash value',   anotherclass: 'hash value' } 

is equivalent to:

{   :someclassa => 'hash value',   :anotherclass => 'hash value' } 

the keys symbols. in "new" literal hash syntax keys treated literals cast symbols (provided valid syntax).

to use constants, ranges or other type of object can dream keys need use hashrockets:

{   someclassa => 'hash value',   anotherclass => 'hash value' } 

is practice?

its technique used in few limited cases. example replace series of if statements.

def foo(bar)   if bar.is_a? someclassa     'hash value'   end   if bar.is_a? anotherclass     'another value'   end end  def foo(bar)   {     someclassa => 'hash value',     anotherclass => 'another value'   }[bar] end 

but rather use case statement there anyways clearer in intent , more flexible.

are there drawbacks in terms of performance or testing?

each hash create have keys point exact same objects in memory if using symbols.

one big gotcha rails monkey-patches const_missing autoload files - when reference class name rails load file file system memory. why declare associations with:

class foo < applicationrecord   belongs_to :bar, class_name: "baz" end 

it lets rails instead lazy load baz when needed. same example above by:

def foo(bar)   {     'someclassa' => 'hash value',     'anotherclass' => 'another value'   }[bar.name] end 

Comments

Popular posts from this blog

resizing Telegram inline keyboard -

command line - How can a Python program background itself? -

php - "cURL error 28: Resolving timed out" on Wordpress on Azure App Service on Linux -