DRYing up Rock Paper Scissors

前端 未结 4 949
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-25 04:18

I\'m a novice ruby programmer and although this code works, I\'m wondering how I can improve it. I have very limited knowledge on lambdas and procs and the like, but any advice

4条回答
  •  抹茶落季
    2021-01-25 04:37

    You can build a hash that contains the pick and which option lose against that pick:

    hash = {'scissors' => 'paper', 'rock' => 'scissors', 'paper' => 'rock'}
    

    Then you check if the machine pick is the same like you did:

    roll_ops = ["rock", "paper", "scissors"]
    pick = roll_ops.sample
    if roll == pick
    

    And the win/lose condition becomes something like this:

    if hash[roll] == pick
      "win"
    else
      "lose"
    end
    

    Nice and clean with just 2 conditions.

提交回复
热议问题