Ruby 3.0 adds `Hash#except` and `ENV.except`

Ruby adds instance method #except to Hash.

This method returns a new hash, which includes everything from the original hash except the given keys.

Before

Let’s say, we want to exclude the key :fries from:

{food: "Burger", beverage: "Coke", fries: "large"}

If we are using Rails, we can use except from the Active Support to achieve this:

(Rails 6.0.3.3)
2.7.1 > {food: "Burger", beverage: "Coke", fries: "large"}.except(:fries)
 => {:food=>"Burger", :beverage=>"Coke"}

Similarly, we can accomplish the same in Ruby like this:

2.7.1 > {food: "Burger", beverage: "Coke", fries: "large"}.slice(:food, :beverage)
 => {:food=>"Burger", :beverage=>"Coke"}

In the above example, we selected the keys that we need instead of excluding them.

After

We can now use Hash#except natively in Ruby:

irb(main) > {food: "Burger", beverage: "Coke", fries: "large"}.except(:fries)
=> {:food=>"Burger", :beverage=>"Coke"}

We can also call except with multiple arguments:

irb(main)>  {food: "Burger", beverage: "Coke", fries: "large"}.except(:food, :fries)
=> {:beverage=>"Coke"}

It’s safe to pass an irrelevant/unknown argument to except:

irb(main)>  {food: "Burger", beverage: "Coke", fries: "large"}.except(:stake)
=> {:food=>"Burger", :beverage=>"Coke", :fries=>"large"}

ENV

ENV is a hash-like accessor for environment variables.

The support for except is also added for ENV:

irb(main)> ENV.clear
=> {}
irb(main)> ENV
=> {}
irb(main)> ENV["laptop"] = "Macbook"
irb(main)> ENV["company"] = "Apple"
irb(main)> ENV.except("laptop")
=> {"company"=>"Apple"}

Need help on your Ruby on Rails or React project?

Join Our Newsletter