Skip to content

Instantly share code, notes, and snippets.

@benkoshy
Created July 1, 2025 09:16
Show Gist options
  • Save benkoshy/fcbb21e6148add705e9491162e1e2792 to your computer and use it in GitHub Desktop.
Save benkoshy/fcbb21e6148add705e9491162e1e2792 to your computer and use it in GitHub Desktop.
An example of then
# https://benkoshy.github.io/2024/12/09/then-ruby-keyword.html
# this is a contrived example
# experiment with it in an IRB console.
# we want to:
# take a string
# add convert it to an int
# add 1 to that
# and then cube it
# returning the result
def operation_1(a)
a_int = (a.to_i)
sum = a_int + 1
cube = sum ** 3
return cube
end
# is it pleasant to read?
puts "operation_1 is: #{operation_1("3")}"
# => operation_1 is: 64
# notice how the input of one function
# is an input into another?
# we can write the same thing like this:
def operation_2_dense(a)
(a.to_i + 1) ** 3
end
puts "operation_2_dense is: #{operation_2_dense("3")}"
# => operation_1 is: 64
# but is it readable?
# you can also curry it like so:
def curry(a)
a.then { |i| i.to_i }
.then { |i| i + 1 }
.then { |i| i ** 3 }
end
puts "curry is #{curry("3")}"
# => curry is 64
def add_one(i)
i + 1
end
def cube(i)
i ** 3
end
def curry_2(a)
a.then { |i| i.to_i }
.then { |i| add_one(i) }
.then { |i| cube(i) }
end
puts "curry_2 is #{curry_2("3")}"
# => curry_2 is 64
# if you want something more readable.
# and if you like, you could put add_one and cube
# into a mixin. The implementation details are hidden
# and you can cleanly / elegantly express
# what you want.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment