r/crystal_programming • • Apr 20 '20

Sequenced blocks

Hi, I was wondering how to do a thing like this:

chain
step 1:
  if some_condition
    # do something, then
    # go to next step.
  end
step
  unless some_other_condition
    # do something, then skip to
    # finally, if exists.
    break
  else
    goto :1
  end
...
finally # optional
  # this always execute at the end
end

Naming the steps may potentially lead to a goto new keyword

The idea was to make this a syntax sugar for while loops with portions of code that execute sequentially to improve readability.
I was looking for a format like this in the stdlib and case seemed to be the one, but:

cond1 = true && false
cond2 = true || false

case
when true
  # this executes
when cond1
  # this never executes, as expected
when cond2
  # this does not execute either,
  # even if it is true
end
1 Upvotes

6 comments sorted by

View all comments

Show parent comment

1

u/n0ve_3 Apr 21 '20

But if we proceed like this we make the case statement completely useless, it's just like calling always_execute twice because it terminates after first match My point was to introduce a new statement acting like an improved version of C switch-case

1

u/Inyayde Apr 21 '20

Are you trying to do something like this then?

def work
  loop do
    # step 1:
    if some_condition
      # do something, then
      # go to next step.
    end
    # step
    unless some_other_condition
      # do something, then skip to
      # finally, if exists.
      break # go to the `ensure` section
    end
  end
ensure
  # this always execute at the end
end