Class: Picker
- Inherits:
-
Object
- Object
- Picker
- Defined in:
- lib/subcl/picker.rb
Instance Method Summary collapse
-
#initialize(ary) ⇒ Picker
constructor
A new instance of Picker.
- #pick ⇒ Object
- #validate(pickNum) ⇒ Object
Constructor Details
#initialize(ary) ⇒ Picker
Returns a new instance of Picker.
2 3 4 5 6 7 |
# File 'lib/subcl/picker.rb', line 2 def initialize(ary) @available = ary if ary.empty? then raise ArgumentError, "Cannot initialize Picker with an empty array!" end end |
Instance Method Details
#pick ⇒ Object
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 46 47 48 49 50 51 52 53 54 55 |
# File 'lib/subcl/picker.rb', line 9 def pick choices = {} #TODO add type column when multiple types are available counter_padding = @available.length.to_s.length i = 1 @available.each do |elem| choices[i] = elem #TODO add padding for numbers with one digit $stderr.print "[#{i.to_s.rjust(counter_padding)}] " yield(elem) i = i + 1 end begin picks = [] valid = true $stderr.print "Pick any: " choice = $stdin.gets return @available if choice.chomp == 'all' choice.split(/[ ,]+/).each do |part| possibleRange = part.split(/\.\.|-/) if possibleRange.length == 2 start = possibleRange[0].to_i stop = possibleRange[1].to_i [start, stop].each do |num| valid = validate(num) end (start..stop).each do |num| picks << choices[num] end elsif validate(num = part.to_i) picks << choices[num] else valid == false end end end while !valid return picks end |
#validate(pickNum) ⇒ Object
57 58 59 60 61 62 63 64 65 |
# File 'lib/subcl/picker.rb', line 57 def validate(pickNum) #no -1, we start filling choices{} at 1 if pickNum > 0 and pickNum <= @available.length true else $stderr.puts "Invalid pick. Try again." false end end |