Ruby Advanced Guide

In this article, I will introduces some concepts of Ruby that not all Ruby developers know about

Screen Shot 2018-06-12 at 11.14.29 AM

Block

Is a way to group a short piece of code as a replacement of do … end. It’s not an object, so it cannot be passed as a parameter in a function.

[1, 2, 3].map { |e| e + 1 } # [2, 3, 4]

Proc

Proc is another way we use to shorten our code. Unlike Block, when using Proc, we instantiate an object, and then we can reuse that object in argument list as block

p = Proc.new { |e| e + 1 }
[1, 2, 3].map(&p) # [2, 3, 4]
p.object_id # 47417179317860
p.class # Proc

or in a method as a parameter

def proc_in_method arr, proc
  proc.call(arr)
end
proc = Proc.new { |arr| arr.sum }
proc_in_method [1, 2, 3], proc

Continue reading Ruby Advanced Guide