Monkey Patch Your Way to Ruby 2.3

Numeric #positive & #negative

Works on any subclass of Numeric

# Fixnum
1.positive? # => true
-1.positive? # => false

1.negative? # => true
-1.negative? # => false

# Float
3.14159.positive? # => true
-3.14159.negative? => ture

0.positive? # => false
0.negative? # => false 

15241578750190522342343242341.positive? # => true

Enumerable #grep & grep_v

Works on any subclass of Numeric

[1,2,3].grep(4) #=> []
[1,2,3].grep(2) #=> [2]
[1,2,3,1].grep(1) #=> [1, 1]

(1..3).grep(3) #=> 3
(1...3).grep(3) #=> 3

["sock", "rock"].grep("rock") #=> ["sock"]
["word", "123"].grep(/\d/) #=> ["123"]

Hash #fetch_values

Works on any subclass of Numeric

h = {
  "cat" => "feline",
  "dog" => "canine",
  "cow" => "bovine",
}

h.fetch_values("cow", "cat")
#=> ["bovine", "feline"]

h.fetch_values("cow", "bird")
#=> KeyError: key not found: "bird"

h.fetch_values("cow", "bird") do |missing_key|
  missing_key.upcase
end
#=> ["bovine", "BIRD"]

Hash #dig

Safely access nested hashes

list = [
  [2, 3],
  [5, 7, 9],
  [ [11, 13], [17, 19] ]
]

list.dig(1, 2)    #=> 9
list.dig(2, 1, 0) #=> 17
list.dig(0, 3)    #=> nil
list.dig(4, 0)    #=> nil

Array #dig

dict = {
  a: { x: 23, y: 29 },
  b: { x: 31, z: 37 }
}

dict.dig(:a, :x) #=> 23
dict.dig(:b, :z) #=> 37
dict.dig(:b, :y) #=> nil
dict.dig(:c, :x) #=> nil

Safely access nested arrays

Did You Mean?

Friendly Error Suggestions for Misspellings

def correctly_spelled 
end

correctly_splled

# NameError: undefined local variable or method `correctly_splled' for main:Object
# Did you mean?  correctly_spelled

Arrry
# NameError: uninitialized constant Arrry
# Did you mean?  Array

@iv = "iv"
iv
# NameError: undefined local variable or method `iv' for main:Object
# Did you mean?  @iv

Class.metheds
# NoMethodError: undefined method `metheds' for Class:Class
# Did you mean?  methods
#                method

Works for:

  • method names
  • class names
  • variable names
  • instance variables
  • class variable names
  • no method errors

Hash “comparison”

Should have just been #contains_subset?

{ type: "dog", name: "Blue" } >= { type: "dog" } #=> true
{ type: "dog", name: "Blue" } >= { type: "cat" } #=> false
{ type: "dog" } >= { type: "dog", name: "blue" } #=> false

Try and implement #contains_subset?

Safe Navigation Or Lonely Operator

Basically #try

u = User.first

u.posts.first.maybe_broken.could_be_broken_here.definetly_broken_by_now


# Rails
u.posts.first
    .try(:maybe_broken)
    .try(:could_be_broken_here)
    .try(:definetly_broken_by_now)

# Ruby 2.3
u.posts.first&.maybe_broken&.could_be_broken_here&.definetly_broken_by_now

Why lonely operator?

This is why

&

Ruby 2.3

By Thomas Hopkins

Ruby 2.3

  • 686