Skip to content

Instantly share code, notes, and snippets.

@rmw
Created May 16, 2012 14:04
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save rmw/2710573 to your computer and use it in GitHub Desktop.
Save rmw/2710573 to your computer and use it in GitHub Desktop.
Extend Ruby Hash with a method to return all keys as symbols
class Hash
def with_sym_keys
self.inject({}) { |memo, (k,v)| memo[k.to_sym] = v; memo }
end
end
require 'spec_helper'
describe Hash do
describe "#with_sym_keys" do
it "should replace string keys with symbols" do
hash = { "a" => 1, "b" => 1 }
hash.with_sym_keys.should == { :a => 1, :b => 1 }
end
end
end
@databyte
Copy link

each_with_object is sometimes easier to read too:

self.each_with_object({}) { |(k,v), memo| memo[k.to_sym] = v }

@rmw
Copy link
Author

rmw commented Jun 18, 2012

oooh. yes, much more readable. Thanks!

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