Beejamin Beejamin - 2 years ago 65
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

'a' => [1...60],
'b' => [60...90],
'c' => [90..999]

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


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

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

Answer Source

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)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download