💾 Archived View for gemlog.blue › users › verachell › 1645235632.gmi captured on 2024-05-10 at 15:29:52. Gemini links have been rewritten to link to archived content

View Raw

More Information

⬅️ Previous capture (2022-03-01)

-=-=-=-=-=-=-

Note: This post is a Gemini space version of my post originally published on July 19, 2021

https version of this post

This is a slightly more advanced version of my previous post on creating callable variants of functions in Ruby while avoiding scope problems.

Callable variants of functions in Ruby

In today's instance, I was creating an error reporting system for a program I was writing.

The error reporting, of necessity, had to emit a message to indicate what was going on. While some errors would be unique messages that only occurred once during the program, other errors could be grouped. For example, one group was "incorrect number of parameters supplied". There were several error messages within my program that fell into this category, so I didn't want to type out the exact same wording each time. I wanted to create a function that could report this sort of error indicating where it happened (of course I had to supply parameters to the messages to show the context).

So here is a very basic sketch of the sort of thing I was doing. I'm writing this here so that I can go back to it easily later. The item I'm really seeking to document here is the arg_c_str function and its call:

def basic_str(str)
  puts "ERROR: #{str}"
end

def complex_str(thing1, thing2, thing3)
  basic_str("#{thing1} #{thing2} #{thing3}")
end

def curried_comp_str
  self.method(:complex_str).curry.("one")
end

def arg_c_str(apex)
  self.method(:complex_str).curry.("header #{apex}")
end

basic_str("hello")
complex_str("banana", "apple", "pear")
curried_comp_str.("two", "three")
arg_c_str("top").call("2", "3")

This program produces:

ERROR: hello
ERROR: banana apple pear
ERROR: one two three
ERROR: header top 2 3

This general approach is helpful when seeking to create flexible callable variants of functions in Ruby.