Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: defining class level hash with default values

Tags:

ruby

i have a basic ruby class:

class LogEntry

end

and what i would like to do is be able to define a hash with a few values like so:

EntryType = { :error => 0, :warning => 1, :info => 2 }

so that i can access the values like this (or something similar):

LogEntry.EntryType[:error]

is this even possible in Ruby? am i going about this the right way?

like image 801
Jason Miesionczek Avatar asked Nov 25 '08 21:11

Jason Miesionczek


2 Answers

You can do this:

class LogEntry
    EntryType = { :error => 0, :warning => 1, :info => 2 }
end

But you want to reference it as

LogEntry::EntryType[:error]
like image 115
Dustin Avatar answered Oct 09 '22 00:10

Dustin


Alternatively you could make a class method:

class LogEntry

  def self.types
    { :error => 0, :warning => 1, :info => 2 }
  end

end

# And a simple test
LogEntry.types[:error].should be_an_instance_of(Hash)
like image 37
Chris Lloyd Avatar answered Oct 09 '22 00:10

Chris Lloyd