Ruby 2.3 new features

Updated . Posted . Visible to the public.

Ruby 2.3.0 has been around since end of 2015. It brings some pretty nice new features! Make sure to read the linked post with its many examples!

Hash#fetch_values

Similar to Hash#fetch, but for multiple values. Raises KeyError when a key is missing.

attrs = User.last.attributes
attrs.fetch_values :name, :email

Hash#to_proc

Turns a Hash into a Proc that returns the corresponding value when called with a key. May be useful with enumerators like #map:

attrs.to_proc.call(:name)
attrs.keys.grep(/name/).map &attrs

Hash comparison

Hashes can now be compared like numbers: <, >, <=, >=, which checks for (proper) subsets.

{a: 1} >= {a: 1} # => true
{a: 1} > {a: 1} # => false

Numeric predicates

Numeric#positive? and Numeric#negative? allow for easy filtering:

[1, -4, 2, -100].select &:positive? # => [1, 2]

Negative grep

Enumerable#grep_v excludes from the result set. It's similar to Rails' #reject:

['foo', 1, 'bar', {}].grep String # => ['foo', 'bar']
['foo', 1, 'bar', {}].grep_v String # => [1, {}]

Further, a safe navigation operator and Array#dig and Hash#dig!.

Dominik Schöler
Last edit
Dominik Schöler
License
Source code in this card is licensed under the MIT License.
Posted by Dominik Schöler to makandra dev (2016-07-12 12:31)