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?

4 Answers 4

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]
Sign up to request clarification or add additional context in comments.

2 Comments

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.
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
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)

Comments

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

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.