Ad space (banner)
๐Ÿ’ŽRuby Lessons
Lesson 29 / 68

Higher-Order Functions (Passing a Block)

In this lesson you will learn the idea of higher-order functions in Ruby so you can write flexible code that takes a block. This is for anyone searching for "Ruby higher-order function block".

Passing another piece of work (a block) as an argument is what makes something a higher-order function. Picture handing over the rules for a job and letting someone else do the work. Giving a comparison rule to .sort is the classic example.

The sample code passes its own comparison rule as a block to sort with nums.sort { |a, b| b <=> a }, sorting in descending order. <=> is the "spaceship operator", which compares two values and returns -1, 0, or 1.

A common stumbling block for beginners is what <=> means. Returning -1 when the left is smaller, 0 when equal, and 1 when larger, it is central to Ruby sorting and takes a moment to get used to.

The map you met earlier is in fact another higher-order function, and part of what makes Ruby so readable. Being able to pass a block as an argument is an idea used everywhere in Ruby code.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Ruby directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)