what is the point of return in Ruby?

前端 未结 7 2152
日久生厌
日久生厌 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:31

    return allows you to break out early:

    def write_code(number_of_errors)
      return "No problem" if number_of_errors == 0
      badness = compute_badness(number_of_errors)
      "WHAT?!  Badness = #{badness}."
    end
    

    If number_of_errors == 0, then "No problem" will be returned immediately. At the end of a method, though, it's unnecessary, as you observed.


    Edit: To demonstrate that return exits immediately, consider this function:

    def last_name(name)
      return nil unless name
      name.split(/\s+/)[-1]
    end
    

    If you call this function as last_name("Antal S-Z"), it will return "S-Z". If you call it as last_name(nil), it returns nil. If return didn't abort immediately, it would try to execute nil.split(/\s+/)[-1], which would throw an error.

提交回复
热议问题