rubyhighline

HighLine: Using gather and answer_or_default


This is my current code for ircd configuration file generator, I'm trying to be able to use answer_or_default for this, and figure out the use of HighLine::Question#gather

Here's the answer_or_default

a = HighLine.new($stdin, $stderr)
connect_pingfreq = a.ask("? ", Integer) do |q|
  q.default = 240
  q.in = 0..300
  # q.answer_or_default
  # gives
  # /var/lib/gems/2.0.0/gems/highline
  # -1.7.8/lib/highline/question.rb:217:in
  # `answer_or_default': wrong number of arguments (0 for 1) (ArgumentError)
end
# I've used it here as
# connect_pingfreq.answer_or_default
# But then gives the error shown
# ? 
# /home/ken/git/shell-scripts/inspigen/generator.rb:48:in `conf': 
# undefined method `answer_or_default' for 240:Fixnum (NoMethodError)

When using answer_or_default inside, I'm not too sure on how to give it its 'answer_string' the documentation says it wants.

And then 240 is the answer given but I can't exactly do anything with.

I'd also like to learn the use of HighLine::Question#gather using this piece of code. Considering I can't quite understand the documentation for it

a = HighLine.new($stdin, $stderr)
a.say "Your <admin> lines.."
admin_name = a.ask "Admin Real Name? "
admin_nick = a.ask "Admin Nick? "
admin_email = a.ask("Admin Email? ") do |q|
  q.validate = /\A([\w+\-].?)+@[a-z\d\-]+(\.[a-z]+)*\.[a-z]+\z/
end

#gather should ask me for 3 lines, name, nick, and email

Either in a hash or array, but I believe a hash would be more easily read.


Solution

  • For your first question, you can just get the answer (or default) from the connect_pingfreq variable. No need to call answer_or_default. Like this:

    a = HighLine.new($stdin, $stderr)
    connect_pingfreq = a.ask("? ", Integer) do |q|
      q.default = 240
      q.in = 0..300
    end
    
    puts connect_pingfreq
    

    This will output either the answer the user entered or the default of 240.