84 lines
1.6 KiB
Ruby
84 lines
1.6 KiB
Ruby
# Défi : interpréter une commande
|
|
#
|
|
# Tu construis une petite interface terminal.
|
|
#
|
|
# Écris la méthode `parse_command(input)`.
|
|
#
|
|
# Entrées possibles :
|
|
#
|
|
# "play 3"
|
|
# "help"
|
|
# "quit"
|
|
#
|
|
# Résultats attendus :
|
|
#
|
|
# parse_command("play 3")
|
|
# => { action: :play, card: 3 }
|
|
#
|
|
# parse_command("help")
|
|
# => { action: :help }
|
|
#
|
|
# parse_command("quit")
|
|
# => { action: :quit }
|
|
#
|
|
# Une commande invalide doit retourner :
|
|
#
|
|
# { action: :invalid }
|
|
#
|
|
# Exemples invalides :
|
|
#
|
|
# "play"
|
|
# "play three"
|
|
# "play 0"
|
|
# "play 3 extra"
|
|
# "hello"
|
|
#
|
|
# Contraintes :
|
|
# - accepte les espaces au début et à la fin ;
|
|
# - `play` n'accepte qu'un entier strictement positif ;
|
|
# - la commande doit respecter exactement une des formes prévues ;
|
|
# - ne lève pas d'exception pour une entrée invalide.
|
|
#
|
|
# Exemples supplémentaires :
|
|
#
|
|
# parse_command(" play 3 ")
|
|
# => { action: :play, card: 3 }
|
|
#
|
|
# parse_command("play 3 extra")
|
|
# => { action: :invalid }
|
|
|
|
def parse_command(input)
|
|
response = {}
|
|
parts = input.strip.split
|
|
|
|
case parts[0]
|
|
when "help"
|
|
if parts.size == 1
|
|
response[:action] = :help
|
|
else
|
|
response[:action] = :invalid
|
|
end
|
|
when "quit"
|
|
if parts.size == 1
|
|
response[:action] = :quit
|
|
else
|
|
response[:action] = :invalid
|
|
end
|
|
when "play"
|
|
if parts.size == 2 && parts[1].match?(/\A\d+\z/) && parts[1].to_i > 0
|
|
response[:action] = :play
|
|
response[:card] = parts[1].to_i
|
|
else
|
|
response[:action] = :invalid
|
|
end
|
|
else
|
|
response[:action] = :invalid
|
|
end
|
|
|
|
response
|
|
end
|
|
|
|
print "Entrez une action : "
|
|
input = gets.chomp
|
|
puts parse_command(input)
|