rubyhighline

Randomize the echo char in Highline's ask method?


I am trying to randomize the echo character in the Highline gem's ask method, but could not get it to work. Did I not do this right?

srand
ask("password:  ") { |q| q.echo = ('a'.ord+rand(26)).chr }

The character is randomized for each ask() call, but not each character. The first run will echo the same character, i.e. 'cccc'. The next run will echo 'mmmm', etc.


Solution

  • echo is a variable value used to determine whether to echo output. From the highline source:

    # [echo] Can be set to +true+ or +false+ to control whether or not input will
    # be echoed back to the user.  A setting of +true+ will cause echo to
    # match input, but any other true value will be treated as a String to
    # echo for each character typed.
    

    Your code (('a'.ord+rand(26)).chr) is being evaluated once per ask, stored in the echo variable within highline, and then printed out for each character entered.

    You can't get it to print a different random character per input character without modifying highline.