HiveBrain v1.2.0
Get Started
← Back to all entries
patternrubyMinor

Add data of unknown type to a hash

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
unknownhashtypedataadd

Problem

I don't see any way to refactor this, but something tells me I'm missing something.

if val.instance_of?(Hash) then
    @fields.has_key?(key) ? @fields[key].merge!(val) : @fields.merge!({key => val})
elsif val.instance_of?(Array) then
    @fields.has_key?(key) ? @fields[key].push(val) : @fields.merge!({key => Array.new.push(val)})
else
    @fields.has_key?(key) ? @fields[key]  val})
end


The point of the method is to take a hash and insert a value of different types if the key doesn't exist:

{:key => "value}, {:key = ["value"]}, or {:key => {:k => "value"}}

or append if it does:

{:key=> "value1value2"}, {:key => [["value1"], ["value2"]], {:key => {:k1 => "value1", :k2 => "value2"}}

it does work as intended, so my issue is thinking that there is likely an easier way to do it.

Solution

There are some obvious targets for refactoring, such as Array.new.push(val) instead of [val], but to me this entire code block stinks. The most obvious smell is the type checking necessitated by a lack of duck typing.

Can you explain more about the tensions that lead to this design? I suspect the best solution is further up the context stack than what you have provided.

Context

StackExchange Code Review Q#1663, answer score: 6

Revisions (0)

No revisions yet.