Safe navigation operator

A new operator (&.) has been introduced.
It can be very useful in cases where you need to check if an object is nil
before calling a method on it.
It will return nil if the object equals nil,
otherwise it calls the method on the object.

There are some caveats to consider.
The first version would evaluate to false if user were set to false,
but the safe navigation operator would throw a NoMethodError.
This is similar to Rails’
#try!
method.

Frozen string literals

Until Ruby 2.2, strings were mutable by default in Ruby.
We’re allowed to do something like str[2] = 'z'.
If we want to make strings immutable,
we need to call #freeze on it (eg. str = 'foobar'.freeze).

To make the transition easier,
Ruby 2.3 allows you to optionally make all strings literals frozen by default.
You can enable this by adding a comment
frozen_string_literal: true
at the start of the file.
When enabled, all the string literals in the file are frozen
even without calling #freeze on them.
Note that this only enables the feature on files that have the comment.

This might not seem useful in itself.
Why not use [] to access the elements?
But it gets interesting when we use the & operator to create a proc
and pass it to an Enumerable block.

h={foo: 1,bar: 2,baz: 3}# instead of this:[:foo,:bar].map{|key|h[key]}#=> [1, 2]# we can use this syntax:[:foo,:bar].map(&h)#=> [1, 2]

Hash#fetch_values

This method works like Hash#values_at -
it fetches the values corresponding to the list of keys we pass in.
The difference is that #values_at returns nil when the key doesn’t exist,
while #fetch_values raises a KeyError for keys that aren’t present.

Numeric#positive? and #negative?

Links

Hi, I’m Nithin Bekal.
I work at Shopify in Ottawa, Canada.
Previously, co-founder of
CrowdStudio.in and
WowMakers.
Ruby is my preferred programming language,
and the topic of most of my articles here,
but I'm also a big fan of Elixir.
Tweet to me at @nithinbekal.