Ruby 的返回点是什么? [英] what is the point of return in Ruby?
问题描述
return
和只放一个变量有什么区别,比如下面:
What is the difference between return
and just putting a variable such as the following:
def write_code(number_of_errors)
if number_of_errors > 1
mood = "Ask me later"
else
mood = "No Problem"
end
mood
end
返回
def write_code(number_of_errors)
if number_of_errors > 1
mood = "Ask me later"
else
mood = puts "No Problem"
end
return mood
end
推荐答案
return
让你早点突破:
def write_code(number_of_errors)
return "No problem" if number_of_errors == 0
badness = compute_badness(number_of_errors)
"WHAT?! Badness = #{badness}."
end
如果number_of_errors == 0
,则立即返回没问题"
.但是,正如您所观察到的,在方法的末尾是不必要的.
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.
为了证明 return
立即退出,考虑这个函数:
To demonstrate that return
exits immediately, consider this function:
def last_name(name)
return nil unless name
name.split(/\s+/)[-1]
end
如果你调用这个函数为last_name("Antal S-Z")
,它会返回"S-Z"
.如果您将其称为 last_name(nil)
,则返回 nil
.如果return
没有立即中止,它会尝试执行nil.split(/\s+/)[-1]
,这会抛出错误.
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.
这篇关于Ruby 的返回点是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!