Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

what is the point of return in Ruby?

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

no return

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

return

def write_code(number_of_errors)
  if number_of_errors > 1
    mood =  "Ask me later"
  else
    mood = puts "No Problem"
  end  
  return mood
end
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...