Beejamin Beejamin - 5 months ago 12
Ruby Question

Why is Ruby symbolising my hash keys?

I've come across something odd while writing a Ruby module (a set of helper methods for a Sinatra app). I'm declaring a hash as a constant, with keys as strings. Later, when I attempt to retrieve a value, I get nil. On inspecting the hash, I find that the keys have been converted to symbols. What's going on?

Here's a simplified example:

module HelperModule

RANGES = {
'a' => [1...60],
'b' => [60...90],
'c' => [90..999]
}.freeze

def find_range(key)
RANGES[key] # Returns nil when key is 'a', 'b' or 'c'
end

end


Inspecting RANGES yields:
{:a=>[1...60], :b=>[60...90], :c=>[90..999]}
.

I can work around it easily enough by converting key
.to_sym
, but I want to understand what's happening here.

Answer

It's something in your environment that alters Hash.

Start with looking into RANGES.class.ancestors, also look for refinements (those you probably have to grep for using)