Skip to content

Instantly share code, notes, and snippets.

@bogdanRada
Created December 14, 2012 15:47
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bogdanRada/4286379 to your computer and use it in GitHub Desktop.
Save bogdanRada/4286379 to your computer and use it in GitHub Desktop.
def symbolize_keys(obj)
case obj
when Array
obj.inject([]){|res, val|
res << case val
when Hash, Array
symbolize_keys(val)
else
val
end
res
}
when Hash
obj.inject({}){|res, (key, val)|
nkey = case key
when String
key.to_sym
else
key
end
nval = case val
when Hash, Array
symbolize_keys(val)
else
val
end
res[nkey] = nval
res
}
else
obj
end
end
@majedbojan
Copy link

Hello buddy there is an error when i try to convert string like "Content-Type" to symbol it converts to :"Content-Type"

    25:         }
    26:       when Hash
    27:         obj.inject({}){|res, (key, val)|
    28:           nkey = case key
    29:           when String
 => 30:             binding.pry
    31:             key.to_sym
    32:           else
    33:             key
    34:           end
    35:           nval = case val

[1] pry(SimpleHelper::Utils)> key
=> "Content-Type"
[2] pry(SimpleHelper::Utils)> key.to_sym
=> :"Content-Type"
[3] pry(SimpleHelper::Utils)> key
=> "Content-Type"

@softbrada
Copy link

softbrada commented Jan 1, 2020

Hello. That is expected. That is how a string gets converted to a symbol. What you are looking for is key.underscore.to_sym. Feel free to update the code for your own needs. You need activesupport gem for that though

@Maddin2Code
Copy link

Maddin2Code commented Mar 28, 2022

@softbrada Thank you for this. I use your code as core extension of the Hash class. This way I avoid to use larger Rails gems.

class Hash
  def symbolize_keys
    case self
    when Array
      self.inject([]){|res, val|
        res << case val
        when Hash, Array
          symbolize_keys(val)
        else
          val
        end
        res
      }
    when Hash
      self.inject({}){|res, (key, val)|
        nkey = case key
        when String
          key.to_sym
        else
          key
        end
        nval = case val
        when Hash, Array
          symbolize_keys(val)
        else
          val
        end
        res[nkey] = nval
        res
      }
    else
      self
    end
  end
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment