Bound_cond - a `cond` that lets you thread (bind) interim variables through its clauses

For those of us still caring about the code readability (in the age of LLMs), this tiny library can replace nested ifs in situations when with is inadequate (when there’s more than just one success/happy path), so a cond would suit better, but cond itself doesn’t support lazy binding of variables that become accessible to subsequent clauses down the road.

Below is a simple example (from README) of how to use it.

So, instead of having something like the following if nesting (or an analog cond nesting):

foo =
  if in_range?( x, y) do
    n
  else
    last = get_last( x)
    post = get_pos( y)

    if pos > last do
      last
    else
      pos
    end
  end

BoundCond enables a more declarative/readable approach:

foo =
  bound_cond do
    in_range?( x, y) -> 
      n

    :bind ->
      last = get_last( x)
      pos = get_pos( y)

      pos > last -> 
        last
      
      true -> 
        pos
  end

Any number of :bind’s is permitted. What maters is that a :bind doesn’t count as a real clause, so there need to be some actual clauses underneath it, for otherwise it wouldn’t make any sense.

1 Like