Skip to content

Commit

Permalink
AS guide: documents slice and slice!
Browse files Browse the repository at this point in the history
  • Loading branch information
fxn committed Sep 14, 2009
1 parent 1931335 commit 55ffc26
Showing 1 changed file with 29 additions and 0 deletions.
29 changes: 29 additions & 0 deletions railties/guides/source/active_support_overview.textile
Expand Up @@ -1321,6 +1321,35 @@ def create_has_many_reflection(association_id, options, &extension)
end
</ruby>

h4. Slicing

Ruby has builtin support for taking slices out of strings and arrays. Active Support extends slicing to hashes:

<ruby>
{: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
</ruby>

If the receiver responds to +convert_key+ keys are normalized:

<ruby>
{:a => 1, :b => 2}.with_indifferent_access.slice("a")
# => {:a => 1}
</ruby>

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:

<ruby>
hash = {:a => 1, :b => 2}
rest = hash.slice!(:a) # => {:b => 2}
hash # => {:a => 1}
</ruby>

h4. Indifferent Access

The method +with_indifferent_access+ returns an +ActiveSupport::HashWithIndifferentAccess+ out of its receiver:
Expand Down

0 comments on commit 55ffc26

Please sign in to comment.