From 924d9066cfabf8b410fa06a43a63b2264106fadc Mon Sep 17 00:00:00 2001 From: Xavier Noria Date: Sun, 13 Sep 2009 20:52:48 +0200 Subject: AS guide: documents stringify_keys and stringify_keys! --- .../guides/source/active_support_overview.textile | 34 +++++++++++++++++++++- 1 file changed, 33 insertions(+), 1 deletion(-) (limited to 'railties') diff --git a/railties/guides/source/active_support_overview.textile b/railties/guides/source/active_support_overview.textile index 3eae3f7421..6305ed6d69 100644 --- a/railties/guides/source/active_support_overview.textile +++ b/railties/guides/source/active_support_overview.textile @@ -1166,7 +1166,9 @@ hash1.diff(hash2).diff(hash2) == hash1 Diffing hashes may be useful for error messages related to expected option hashes for example. -h4. Removing Keys +h4. Working with Keys + +h5. +except+ and +except!+ The method +except+ returns a hash with the keys in the argument list removed, if present: @@ -1190,6 +1192,36 @@ params[:account] = params[:account].except(:plan_id) unless admin? There's also the bang variant +except!+ that removes keys in the very receiver. +h5. +stringify_keys+ and +stringify_keys!+ + +The method +stringify_keys+ returns a hash that has a stringified version of the keys in the receiver. It does so by sending +to_s+ to them: + + +{nil => nil, 1 => 1, :a => :a}.stringify_keys +# => {"" => nil, "a" => :a, "1" => 1} + + +The result in case of collision is undefined: + + +{"a" => 1, :a => 2}.stringify_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 +ActionView::Helpers::FormHelper+ defines: + + +def to_check_box_tag(options = {}, checked_value = "1", unchecked_value = "0") + options = options.stringify_keys + options["type"] = "checkbox" + ... +end + + +The second line can safely access the "type" key, and let the user to pass either +:type+ or "type". + +There's also the bang variant +stringify_keys!+ that stringifies 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