Skip to content
Daniel Berger edited this page Jul 9, 2022 · 3 revisions

What's a hash slice?

In standard Ruby you may only reference single elements of a hash, both for reading and writing. A hash "slice" is just like it sounds, a reference to multiple elements of a hash.

The hashslice library allows you to reference, and assign, multiple hash keys simultaneously. Typically they are returned or assigned as arrays. However, they may also be returned as hashes (a "sub hash") if you so desire.

Synopis

require 'hashslice'

hash = {'a' => 1, 'b' => 2, 'c' => 3}

# Slice reference
hash['a', 'b'] # [1, 2]
hash['a']      # 1

# Slice assignment
hash['a', 'b'] = 7, 8

hash # {'a' => 7, 'b' => 8, 'c' => 3}

# Sub hash
hash.hash_of('a', 'b') # {'a' => 1, 'b' => 2}

Comments

Hash slices are baked into Perl, which is what originally inspired this library. Despite attempts to bake this feature into core Ruby, it has been ignored.

Clone this wiki locally