Ruby 2.2 useful methods

We recently have switched one of our apps to Ruby 2.2 and I did not know what exactly is behind it so I decided to do a research and learn something new. A detailed list of changes introduced in version 2.2 can be found in Github.

`Method#super_method`

class Animal
  def sound
    "Whoa"
  end
end

class Dog < Animal def sound "Hau Hau" end end dog = Dog.new dog.public_method(:sound).call => "Hau Hau"

dog.public_method(:sound).super_method.call
=> "Whoa"

`Enumerable#slice_after`

array = (1..10).to_a
=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

array.slice_after(&:even?).to_a
=> [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]]

`Enumerable#max` and `Enumerable#min`

array = (1..10).to_a
=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

array.max 2
=> [10, 9]

array.min 3
=> [1, 2, 3]

`Enumerable#max_by` and `Enumerable#min_by`

words = %w(a ab abc)
=> ["a", "ab", "abc"]

words.max_by 2, &:length
=> ["abc", "ab"] # array

words.min_by &:length
=> "a" # string

`File#birthtime`

This one is very self explanatory, it returns the birth time for the named file:

File.birthtime('ruby-2-2.jpg')
=> 2015-05-12 16:59:04 +0200

`Kernel#itself`

`itself` method was the most mysterious for me at the beginning, it returns the object it is called on:

1.itself
=> 1

"Foo".itself
=> "Foo"

OK, but what can it be used for? Maybe for grouping?

random_array = [1, 2, 3] * 3
 => [1, 2, 3, 1, 2, 3, 1, 2, 3]

random_array.group_by(&:itself)
=> {1=>[1, 1, 1], 2=>[2, 2, 2], 3=>[3, 3, 3]}

It works!

What else?

The above methods are the most useful for me. There are other methods introduced in Ruby 2.2 like `Float#next_float`, `String#unicode_normalize` and `Matrix#first_minor` so if you are looking for more details check Github NEWS.

 

Igor Springer

I build web apps. From time to time I put my thoughts on paper. I hope that some of them will be valuable for you. To teach is to learn twice.

 

Leave a Reply

Your email address will not be published. Required fields are marked *