HW impossibility?: “Create a rock paper scissors program in ruby WITHOUT using conditionals”

后端 未结 8 1882
我寻月下人不归
我寻月下人不归 2021-02-14 16:50

I\'m in an introductory software development class, and my homework is to create a rock paper scissors program that takes two arguments (rock, paper), etc, and returns the arg t

相关标签:
8条回答
  • 2021-02-14 17:50

    pguardiario's solution above can be modified per the below to show both (1) which player won (as opposed to the choice of object that won) and (2) the result when there is a draw:

    def rps(p1, p2)
       @results = {
       'rock/paper' => "Player 2 won!",
       'rock/scissors' => "Player 1 won!",
       'paper/scissors' => "Player 2 won!",
       'paper/rock' => "Player 1 won!",
       'scissors/paper' => "Player 1 won!",
       'scissors/rock' => "Player 2 won!",
       'rock/rock' => "Draw!",
       'scissors/scissors' => "Draw!",
       'paper/paper' => "Draw!"
       }
    
       @results["#{p1}/#{p2}"]
    end
    
    rps("rock", "rock")     => "Draw!"
    rps("rock", "scissors") => "Player 1 won!"
    rps("rock", "paper")    => "Player 2 won!"
    

    ...etc

    0 讨论(0)
  • 2021-02-14 17:51
    def winner(p1, p2)
      wins = {rock: :scissors, scissors: :paper, paper: :rock}
      {true => p1, false => p2}[wins[p1] == p2]
    end
    

    winner(:rock, :rock) # => :rock d'oh! – tokland

    Per @sarnold, leaving this as an exercise for the student :).

    0 讨论(0)
提交回复
热议问题