1 Replies - 2481 Views - Last Post: 14 February 2014 - 09:19 PM

#1 Lemur  Icon User is offline

  • Pragmatism over Dogma
  • member icon


Reputation: 1372
  • View blog
  • Posts: 3,469
  • Joined: 28-November 09

Prompt

Post icon  Posted 13 February 2014 - 09:31 PM

def prompt(name: '', matches: '')
  while true
    print "#{name}: "; answer = gets.chomp
    return answer if Array(matches).all? { |match| match === answer }
    puts "Invalid!"
  end
end



To make it even more useful, I suggest you do this:
class Array
  def === other
    self.include? other || self == other
  end
end



With both of those, you can do this:
name   = prompt name: 'name',   matches: [/\w{3,}/, /^br/]
rating = prompt name: 'rating', matches: %w(G PG PG-13 R NC-17 X)



Is This A Good Question/Topic? 2
  • +

Replies To: Prompt

#2 Lemur  Icon User is offline

  • Pragmatism over Dogma
  • member icon


Reputation: 1372
  • View blog
  • Posts: 3,469
  • Joined: 28-November 09

Re: Prompt

Posted 14 February 2014 - 09:19 PM

...or let's extent its power with Izzy like so:

# gem install izzy

class Object; include Izzy end

def prompt(name: '', matches: '', type: 'all')
  while true
    print "#{name}: "; answer = gets.chomp
    m = "matches_#{type}"
    return answer if answer.responds_to? m && answer.send matches
    puts "Invalid!"
  end
end



Allowing you to take it a few steps further, or do the same:
prompt(
  name: 'Date not in this century', 
  matches: -> d { (2000..3000) === d.scan(/\d{4}/) },
  type: 'none'
)

prompt(
  name: 'Odd number or above 10',
  matches: [
    -> d { d.odd? }, -> d { d > 10 }
  ],
  type: 'any'
)



Of course you can always use negating conditions, but there are sure to be interesting ways to use this.
Was This Post Helpful? 1
  • +
  • -

Page 1 of 1