The Crystal Programming Language Forum

Best way to send Ctrl-Chars over a Channel?

Is there a way to write this shorter and better readable ?
‘\u{3}’,"\u0003", ctrl-c - can this be written in the same style on sender and receiver side ?
channel.send(char.not_nil!.to_s) - is it shorter possible ?

channel = Channel(String).new
spawn do  #handle stdin input char by char - do until ctrl-c pressed
        while (char = STDIN.raw &.read_char) != '\u{3}'    #ctrl-c

loop do  #do until cttrl-c
  r = channel.receive
  if r == "\u0003"  #handle ctrl-c from channel

Well you want to avoid not_nil! where possible, also indenting while blocks helps for readability.

In this case though, since you know char is not nil and you’re turning it into a string anyway you can actually just skip the not_nil! call and do char.to_s directly.

Normally I’d recommend you use something like my Term::Reader for this, especially if you plan on handling more escape codes, but since this seems to be a learning thing I’d recommend you keep trying to figure it out.