Ruby 2.3 Notes

A few more notes about changes coming in Ruby 2.3

More predicates

Numbers have positve? and negative? predicates

irb(main):001:0> sample = -5..5
=> -5..5
irb(main):002:0> sample.select(&:positive?)
=> [1, 2, 3, 4, 5]
irb(main):003:0> sample.select(&:negative?)
=> [-5, -4, -3, -2, -1]
irb(main):004:0> sample.select(&:odd?)
=> [-5, -3, -1, 1, 3, 5]
irb(main):005:0> sample.select(&:even?)
=> [-4, -2, 0, 2, 4]

Frozen string literals

A pragma comment at the top of a ruby file will now freeze all string literals declared in that file. Mostly, this is to help performance.

# frozen_string_literal: true
"test".frozen? # => true
"brrr".dup.frozen? # => false

Rubucop will nag you every time you create a file without this magic comment, since the intention is that come Ruby 3.0, all strings will be frozen by default.

Hash comparisons

<= and >= operators for hashes have been introduced for identifying supersets and subsets.

irb(main):001:0> superset = {colour:'green', size:'large', weight:'heavy'}
=> {:colour=>"green", :size=>"large", :weight=>"heavy"}
irb(main):002:0> subset = {size:'large'}
=> {:size=>"large"}
irb(main):003:0> subset <= superset
=> true
irb(main):004:0> subset >= superset
=> false
irb(main):005:0> test = {size:'small'}
=> {:size=>"small"}
irb(main):006:0> test <= superset
=> false
Tagged: | ruby | ruby-2-3 |