From 119040fafbbc48ae0dec867663edab3d744fc8e6 Mon Sep 17 00:00:00 2001 From: Xavier Noria Date: Sun, 13 Sep 2009 21:04:10 +0200 Subject: AS guide: documents symbolize_keys and symbolize_keys! --- .../guides/source/active_support_overview.textile | 32 ++++++++++++++++++++++ 1 file changed, 32 insertions(+) (limited to 'railties') diff --git a/railties/guides/source/active_support_overview.textile b/railties/guides/source/active_support_overview.textile index 6305ed6d69..b6da20314a 100644 --- a/railties/guides/source/active_support_overview.textile +++ b/railties/guides/source/active_support_overview.textile @@ -1222,6 +1222,38 @@ The second line can safely access the "type" key, and let the user to pass eithe There's also the bang variant +stringify_keys!+ that stringifies keys in the very receiver. +h5. +symbolize_keys+ and +symbolize_keys!+ + +The method +symbolize_keys+ returns a hash that has a symbolized version of the keys in the receiver, where possible. It does so by sending +to_sym+ to them: + + +{nil => nil, 1 => 1, "a" => "a"}.symbolize_keys +# => {1 => 1, nil => nil, :a => "a"} + + +WARNING. Note in the previous example only one key was symbolized. + +The result in case of collision is undefined: + + +{"a" => 1, :a => 2}.symbolize_keys +# => {:a => 2}, in my test, can't rely on this result though + + +This method may be useful for example to easily accept both symbols and strings as options. For instance +ActionController::UrlRewriter+ defines + + +def rewrite_path(options) + options = options.symbolize_keys + options.update(options[:params].symbolize_keys) if options[:params] + ... +end + + +The second line can safely access the +:params+ key, and let the user to pass either +:params+ or "params". + +There's also the bang variant +symbolize_keys!+ that symbolizes keys in the very receiver. + h4. Indifferent Access The method +with_indifferent_access+ returns an +ActiveSupport::HashWithIndifferentAccess+ out of its receiver: -- cgit v1.2.3