Collin Donnell

April 13, 2021

An iOS Developer Learns Ruby, Part 2: Blocks and Callbacks

In Swift and Objective-C, it’s common to use a block/closure as a callback method when a method or function finishes what it’s doing, or there’s some update. 

Here’s a contrived example:

func sum(first: Int, second: Int, completion: (Int)->()) {
    completion(first + second);

sum(first: 3, second: 2) { sum in
    print("The value of sum is \(sum)")
    // The value of sum is 5

In Ruby, I kept seeing methods that looked like this:

my_array.each do |item|
  # do something

I knew they were called “blocks” but didn’t know how they worked until I looked it up. Turns out you can do the exact same thing in Ruby I did above in Swift.

def sum(first, second)
  yield first + second

do_something(2, 3) do |sum|
  puts "The value of sum is #{sum}"

The code between in the do/end block is almost identical to the Swift version. One thing that’s different in Ruby is that you can omit the block parameter if you’re using the yield statement. You can also yield multiple times from the same method, just like calling a Swift block repeatedly.

def powers_of_two(pow)
  value = 1
  prev = value
  pow.times do
    value += prev
    prev = value
    yield value

powers_of_two(8) do |val|
  puts val
  # 2, 4, 8, 16, 32, 64, 128, 256