5

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?

Jason Miesionczek
  • 14,268
  • 17
  • 76
  • 108

4 Answers4

7

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
  • 89,080
  • 21
  • 111
  • 133
  • 1
    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. – Grant Hutchins Nov 29 '08 at 07:02
  • 1
    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 – Grant Hutchins Nov 29 '08 at 07:03
1

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
  • 12,100
  • 7
  • 36
  • 32
0

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
  • 36,755
  • 28
  • 133
  • 162
0

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
  • 23,070
  • 14
  • 64
  • 77