tags:

views:

544

answers:

4

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?

+3  A: 

You can do this:

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

But you want to reference it as

LogEntry::EntryType[:error]
Dustin
While it only matters whether the first letter is capitalized or not, I believe that it's more idiomatic Ruby to use ENTRY_TYPE instead of EntryType for a constant. CamelCase is generally used for Module and Class names only.
nertzy
Also, if you don't want the Hash object to be modified in-place, you will want to do ENTRY_TYPE = { :error => 0, :warning => 1, :info => 2 }.freeze
nertzy
+1  A: 

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)
Chris Lloyd
+1  A: 

Why do you need a hash?

Can you not just declare the entry types on the LogEntry class?

class LogEntry
  @@ErrorType = 0
End

LogEntry.ErrorType
Toby Hede
A: 

I'm curious why you can't just make @error_type an instance variable on LogEntry instances?

class LogEntry
  attr_reader :type
  ERROR_RANKING = [ :error, :warning, :info, ]
  include Comparable

  def initialize( type )
    @type = type
  end

  def <=>( other )
    ERROR_RANKING.index( @type ) <=> ERROR_RANKING.index( other.type )
  end
end

entry1 = LogEntry.new( :error )
entry2 = LogEntry.new( :warning )

puts entry1.type.inspect
#=> :error
puts entry2.type.inspect
#=> :warning
puts( ( entry1 > entry2 ).inspect )
#=> false
puts( ( entry1 < entry2 ).inspect )
#=> true

But see also Ruby's built in logging library, Logger.

Pistos