↖️ Show all posts

Special treatment for last element in an Array

This example only needs a list and a function to DRY it all up. Depending on the expected size of the list, one could set variable that stores the count value.

arr = [1, 2, 3, 4, 5]

def power(x)
    puts x**x
    yield if block_given?
end

arr.take(arr.count - 1).each {|x| power(x) }
# 1
# 4
# 27
# 256

power(arr.last) { puts "last element" }
# 3125
# last element

“What’s that yield?”, you might ask.

Mastering Ruby blocks in 5 minutes


⬅️ Read previous Read next ➡️