From 55ffc26b39a5f0b752999361a18ed69c745eda72 Mon Sep 17 00:00:00 2001 From: Xavier Noria Date: Tue, 15 Sep 2009 01:55:54 +0200 Subject: AS guide: documents slice and slice! --- .../guides/source/active_support_overview.textile | 29 ++++++++++++++++++++++ 1 file changed, 29 insertions(+) (limited to 'railties') diff --git a/railties/guides/source/active_support_overview.textile b/railties/guides/source/active_support_overview.textile index 9682a6ee4b..352feb96fb 100644 --- a/railties/guides/source/active_support_overview.textile +++ b/railties/guides/source/active_support_overview.textile @@ -1321,6 +1321,35 @@ def create_has_many_reflection(association_id, options, &extension) end +h4. Slicing + +Ruby has builtin support for taking slices out of strings and arrays. Active Support extends slicing to hashes: + + +{:a => 1, :b => 2, :c => 3}.slice(:a, :c) +# => {:c => 3, :a => 1} + +{:a => 1, :b => 2, :c => 3}.slice(:b, :X) +# => {:b => 2} # non-existing keys are ignored + + +If the receiver responds to +convert_key+ keys are normalized: + + +{:a => 1, :b => 2}.with_indifferent_access.slice("a") +# => {:a => 1} + + +NOTE. Slicing may come in handy for sanitizing option hashes with a white list of keys. + +There's also +slice!+ which in addition to perform a slice in place returns what's removed: + + +hash = {:a => 1, :b => 2} +rest = hash.slice!(:a) # => {:b => 2} +hash # => {:a => 1} + + h4. Indifferent Access The method +with_indifferent_access+ returns an +ActiveSupport::HashWithIndifferentAccess+ out of its receiver: -- cgit v1.2.3