11

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

 3 years ago
source link: https://blog.saeloun.com/2020/09/30/ruby-adds-support-for-hash-except
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

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 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"}

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK