No New Messages
author avatar
Syed Reza
1595717287240 NOTE

Ruby 2.7 - Selected Features

Ruby 2.7 comes with some awesome new changes: https://www.ruby-lang.org/en/news/2019/12/25/ruby-2-7-0-released/

Default Block Params

This is one of my favorite additions to the language because typing out {|e| ... } gets painful after a while.

Here is Matz's comment on the syntax ultimately chosen for this: https://bugs.ruby-lang.org/issues/15723#note-126

Example:

# before Ruby 2.7
(1..10).map {|e| e * 2 } # =>  [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]

# after Ruby 2.7
(1..10).map { _1 * 2 } # =>  [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]

That's a savings of 2 characters!

Perhaps more importantly, the new syntax has a lot less visual noise.

You can use this just easily for Procs and Lambdas.

times_two_proc = Proc.new { _1 * 2 }
times_two_lam = ->{ _1 * 2 }

(1..10).map(&times_two_proc)
(1..10).map(&times_two_lam)

Just for fun, let's see how Perl6 (Raku) does it.

Raku: Using Map

(1..10).map({ $_ * 2 })

Raku: Using Hyper-Multiply Operator

(1..10) >>*>> 2

Dot Tally

This is certainly one of the smaller changes but I love it. Enumerable#tally gives you a frequency map of value to number of occurrences.

This sort of thing comes up frequently.

In example, Matasano (now cryptopals) has an introductory challenge that involves recognizing a sentence as English. A sinple way to do this is to look at the character frequency table as a vector against the known English frequency vector. The smaller the distance, the more English your sentence.

To get the initial vector, you would previously do something like:

str.each_char.inject(Hash.new(0)) {|h,e| h[e]+=1; h}

but now, it's just:

str.each_char.tally

much shorter!