Created
January 10, 2016 21:09
-
-
Save xvw/57167fe706b1b820c96b to your computer and use it in GitHub Desktop.
Choice
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# coding: utf-8 | |
# Une version "sans sécurité" mais qui explique un peu l'idée | |
class Choice | |
def initialize(prompt) | |
@prompt = prompt | |
@choices = [] | |
end | |
def generic(i) | |
print "you chose #{i}!\n" | |
end | |
def add(title, callback) | |
@choices << [title, method(callback)] | |
return self | |
end | |
def show(prompt = "Your choice?>") | |
print(@prompt+"\n") | |
@choices.each.with_index do |choice, i| | |
printf("#{i+1}.) #{choice[0]}\n") | |
end | |
call_selecter(prompt) | |
end | |
def call_selecter(prompt) | |
print(prompt) | |
i = gets.to_i | |
@choices[i-1][1].call(i) | |
end | |
end | |
class TestChoice < Choice | |
def gagner(i); print "Vous avez gagné!\n"; end | |
def perdre(i); print "Vous avez perdu!\n" ;end | |
end | |
t = Choice.new("A choice") | |
.add("Choix 1", :generic) | |
.add("Choix 2", :generic) | |
.add("Choix 3", :generic) | |
test = TestChoice.new("Que voulez vous faire?") | |
.add('Gagner?', :gagner) | |
.add('Perdre?', :perdre) | |
test.show |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment