what is the point of return in Ruby?

前端 未结 7 2135
日久生厌
日久生厌 2020-12-02 18:20

What is the difference between return and just putting a variable such as the following:

no return

def write_code(number_of_errors)
           


        
相关标签:
7条回答
  • 2020-12-02 18:51

    One small caution for those coming from other languages. Say you have a function like the OP's, and you make use of the "last thing computed" rule to set your return value automagically:

    def write_code(number_of_errors)
      if number_of_errors > 1
         mood = "Ask me later"
      else
         mood = "No Problem"
      end  
    end
    

    and let's say you add a debugging (or logging) statement:

    def write_code(number_of_errors)
      if number_of_errors > 1
         mood = "Ask me later"
      else
         mood = "No Problem"
      end  
      puts "### mood = #{mood}"
    end
    

    Now guess what. You've broken your code, because the puts returns nil, which now becomes the return value from the function.

    The solution is to get in the habit of always explicitly putting the return value on the last line, the way the OP did:

    def write_code(number_of_errors)
      if number_of_errors > 1
         mood = "Ask me later"
      else
         mood = "No Problem"
      end  
      puts "### mood = #{mood}"
      mood
    end
    
    0 讨论(0)
提交回复
热议问题