Syntactic sugar refers to the little bit of ✨ magic ✨ Ruby provides you in writing easier to read and more concise code. In Ruby this means leaving out certain symbols, and spaces or writing some expression with a helper of some kind one of these possibilities is the sandwich method, we look more at it here:
It is common when we begin to handle an array in a each to do it specific actions thing like that:
array = [1, 2, 3, 4]
new_array = []
array.each do |element|
new_array << element * 2
end
new_array
# => [2, 4, 6, 8]
Today I learned how simplified it is to handle this type of interaction by thinking about this magic we talked about before. the first thing that is important here is to remember that the use of each
handle and return the same array and for this reason, it is necessary to create a new_array
variable to inject the new values of the product to element * 2
Most of the time, if you have to use the sandwich method, there is probably a higher-level iterator that you could use that will allow you to perform the function on the array or hash without using the sandwich method. In this case, your best bet would be map
:
array = [1, 2, 3, 4]
array.map do |element|
element * 2
end
# => [2, 4, 6, 8]