DRYing up Rock Paper Scissors

前端 未结 4 1003
爱一瞬间的悲伤
爱一瞬间的悲伤 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:52

    ROLL_OPS = %w[rock paper scissors]
    RESULTS = %w[tie lose win]
    def rps(roll)
      unless i = ROLL_OPS.index(roll)
        return puts "Please input rock paper or scissors".freeze
      end
      pick = ROLL_OPS.sample
      puts "#{pick}, #{RESULTS[(i - ROLL_OPS.index(pick)) % 3]}"
    end
    

提交回复
热议问题