-1

I'm writing an application that stores contest results of running a bunch of metrics. The results have these constraints:

  • A key "dq_reasons" refers to an array of strings
  • All other keys default to the Float 0.0

I like to make these constraints explicit using a custom ContestResult class. I want this class to be a Hash. I can subclass:

MyThing = Class.new(OtherThing)

but I heard subclassing core Ruby classes has downsides. What are my other options? How can I set up a class instance to be a Hash with a default value and preset a "dq_reasons" key to be an empty Array?

Current attempt:

class ContestResult < Hash
  extend Forwardable
  def_delegators :@data, :[], :[]=, :each
  def initialize(lyst)
    @data = Hash.new {|h,k| h[k] = 0.0}
    @data["dq_reasons"] = []
    lyst.each {|li| @data[li]}
  end
  def inspect
    @data
  end
end

Current functionality:

c = ContestResult.new([1,2,3])
# => {"dq_reasons"=>[], 1=>0.0, 2=>0.0, 3=>0.0} 
c[4] # => 0.0
c[3] = 34.5
c # => {"dq_reasons"=>[], 1=>0.0, 2=>0.0, 3=>34.5, 4=>0.0} 
1
  • A reason for the downvote would be appreciated
    – Brad Rice
    Apr 5, 2014 at 19:57

1 Answer 1

0

If I understand your problem correctly you can do

h = {"dq_reasons"=>[]}

and subsequently call Hash#fetch on that. You can provide it with a default value.

h.fetch(4, 0.0)

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.