In this article, I will introduces some concepts of Ruby that not all Ruby developers know about
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