Skip to content

Instantly share code, notes, and snippets.

@bogdanRada
Created December 14, 2012 15:47
Show Gist options
  • 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
@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