Ruby uses an object-oriented approach to programming. In such a language, everything is an object, even simple data types like numbers and strings. This means that in Ruby, each object has its own methods that can change the state of the object or perform some actions on it.
Methods in Ruby
Methods in Ruby are specific instructions that are executed when they are called. To define a method in Ruby, the keyword def is used, followed by the method name (and arguments in parentheses, if needed). After that come the instructions that the method should execute. The method ends with the keyword end.
def say_hello(name'name}"
end
Blocks in Ruby
Blocks in Ruby are sets of instructions that can be considered as anonymous methods.
A popular example of blocks in Ruby is iteration methods such as each, map, and select.
array = [1, 2, 3, 4, 5]
array.each do |number|
puts number * 2
end
Procs in Ruby
Procs, or procedures, are objects that execute a block of code. They, like blocks, execute instructions, but differ in that they are objects, have properties, and can be stored, passed, or returned.
proc = Proc.new { |number| puts number * 2 }
array.each(&proc)
Usually, Procs may seem a bit confusing at first. But with a bit of practice and a detailed understanding of how they work, they will become an integral part of your Ruby development.
What’s the next step? Work with Ruby, define your own methods, create blocks, and work with Procs. The more you practice, the faster you will understand the beauty and efficiency of this language.