Module: Bi

Defined in:
lib/better_input.rb,
lib/better_input/version.rb

Constant Summary collapse

VERSION =
"0.1.3"

Class Method Summary collapse

Class Method Details

.input(question = nil, show_response: false, type: "string") ⇒ Object



2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/better_input.rb', line 2

def self.input(question = nil, show_response: false, type: "string")
  unless question.nil?
    puts question
  end

  loop do
    var = gets.chomp

    case type
    when "int"
      begin
        var = Integer(var)
      rescue ArgumentError
        puts "Err: Please, type a (integer) number."
        next
      end
    when "float"
      begin
        var = Float(var)
      rescue ArgumentError
        puts "Err: Please, type a (float) number."
        next
      end
    when "bool"
      if var.downcase == "true"
        var = true
      elsif var.downcase == "false"
        var = false
      else
        puts "Err: Please, type 'true' or 'false'."
        next
      end
    when "string"
      var = String(var)
    else
      puts "Err: Undefined type."
    end

    if show_response
      puts "User Response: #{var}"
    end
    return var
  end
end