Class: Questions::Question

Inherits:
Object
  • Object
show all
Defined in:
lib/questions/question.rb

Overview

You can ask a question with answers for selection. User can select one answer.

It’s also possible to specify answers as an Hash:

Examples:

Long way

q = Question.new("File does exist, what should be done?")
q.answers = [:skip, :overwrite, :abort]
answer = q.ask
# SHELL:
# $ File does exist, what should be done? [s]kip, [o]verwrite, [a]bort
# s<enter>
answer #=> :skip

Short way

answer = Question.ask "File does exist, what should be done?", [:skip, :overwrite, :abort]
# SHELL:
# $ File does exist, what should be done? [s]kip, [o]verwrite, [a]bort
# s<enter>
answer #=> :skip

Hashish way

answer = Question.ask "File does exist, what should be done?", skip: true, overwrite: false, abort: true
# SHELL:
# $ File does exist, what should be done? [s]kip, [a]bort
# s<enter>
answer #=> :skip

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(question) ⇒ Question

Instantiates a new Question object.

Parameters:

  • question (String)

    This message will be printed



37
38
39
40
# File 'lib/questions/question.rb', line 37

def initialize(question)
  @question = question
  @answers = Answers.new
end

Instance Attribute Details

#answersObject

Returns the value of attribute answers.



32
33
34
# File 'lib/questions/question.rb', line 32

def answers
  @answers
end

#questionObject (readonly)

Returns the value of attribute question.



31
32
33
# File 'lib/questions/question.rb', line 31

def question
  @question
end

Class Method Details

.ask(question, answers) ⇒ Symbol

Asks question.

Examples:

Question.ask("What are you doing?", [:nothing, :cleaning_up])
# SHELL:
# $ What are you doing? [n]othing, [c]leaning up
# n<enter>
# => :nothing

Question with answers as hash.

ask("Do you have a problem?", :yes => true, :no => true)

Parameters:

  • question (String)

    Message that will be printed

  • answers (Array, Hash)

    Answers that are displayed for selection

Returns:

  • (Symbol)

    selected answer



90
91
92
93
94
# File 'lib/questions/question.rb', line 90

def self.ask(question, answers)
  question = Question.new(question)
  question.answers = answers
  question.ask
end

Instance Method Details

#askSymbol

Asks question to user. If user typed wrong indicator, then it will be asked again.

Examples:

without answers

q = Question.new("What?")
q.ask #=> raise Error

with answers

q = Question.new("What?")
q.answers = [:yes, :no]
q.ask #=> :yes if user typed 'y'

Returns:

  • (Symbol)

    selected answer



67
68
69
70
71
72
# File 'lib/questions/question.rb', line 67

def ask
  answers = answers()
  raise "You have to set answers" if answers.empty?
  answer = UserInput.get "#{@question} #{answers}"
  answers[answer.to_sym].instruction || ask
end