Reason #75 • March 16th, 2026

Hash#slice and Hash#except

Welcome to the first day of Hash week at Loving Ruby! ❤️‍🔥

Starting off, we'll look at two methods used to return a subset of a hash: slice and except:

Ruby
person = { name: "John", age: 23, favorite_color: "blue" }

# Get a subset of the hash with only the specified keys
person.slice(:name, :favorite_color)
# => { name: "John", favorite_color: "blue" }

# Get a subset of the hash excluding the specified keys
person.except(:favorite_color)
# => { name: "John", age: 23 }
      
JavaScript
const person = { name: "John", age: 23, favoriteColor: "blue" };

// Get a subset of the object with only the specified keys
const slice = (obj, keys) =>
  Object.fromEntries(
    Object.entries(obj).filter(([key]) => keys.includes(key))
  );
slice(person, ["name", "favoriteColor"]);
// => { name: "John", favoriteColor: "blue" }

// Get a subset of the object excluding the specified keys
const except = (obj, keys) =>
  Object.fromEntries(
    Object.entries(obj).filter(([key]) => !keys.includes(key))
  );
except(person, ["favoriteColor"]);
// => { name: "John", age: 23 }
      

So very convenient!

History

Hash#slice and Hash#except were originally introduced as part of ActiveSupport in Rails 2.0 released in 2007.

Hash#slice was upstreamed to Ruby in version 2.5, released on Christmas 2017.

Hash#except was upstreamed to Ruby in version 3.0, released on Christmas 2020.

Reason #76 ?