【发布时间】:2013-03-03 15:36:31
【问题描述】:
我一直认为 ruby 爱好者选择在 ruby 中隐含返回是因为风格偏好(更少的文字 = 更简洁)。但是,有人可以向我确认,在下面的示例中,您实际上必须使返回隐式,否则预期的功能将不起作用? (预期的功能是能够将句子拆分为单词并为每个单词返回“以元音开头”或“以辅音开头”)
# With Implicit Returns
def begins_with_vowel_or_consonant(words)
words_array = words.split(" ").map do |word|
if "aeiou".include?(word[0,1])
"Begins with a vowel" # => This is an implicit return
else
"Begins with a consonant" # => This is another implicit return
end
end
end
# With Explicit Returns
def begins_with_vowel_or_consonant(words)
words_array = words.split(" ").map do |word|
if "aeiou".include?(word[0,1])
return "Begins with a vowel" # => This is an explicit return
else
return "Begins with a consonant" # => This is another explicit return
end
end
end
现在,我知道肯定有很多方法可以使这段代码更高效、更好,但我这样安排的原因是为了说明隐式返回的必要性。有人可以向我确认确实需要隐式回报,而不仅仅是一种风格选择吗?
编辑: 这是一个示例来说明我要展示的内容:
# Implicit Return
begins_with_vowel_or_consonant("hello world") # => ["Begins with a consonant", "Begins with a consonant"]
# Explicit Return
begins_with_vowel_or_consonant("hello world") # => "Begins with a consonant"
【问题讨论】:
-
很少有关于隐式/隐式回报性能比较的博客 - blog.nerdbucket.com/…。还有一个 - tomafro.net/2009/08/the-cost-of-explicit-returns-in-ruby
-
您能准确定义什么“行不通”吗?隐式返回的例子对我来说很好。
-
很抱歉造成混淆,但带有隐式返回的代码确实有效。我实际上是在说具有显式返回的代码是不能按预期工作的代码。我试图了解这是否是为什么实际上需要隐式返回的用例(因为我一直认为隐式返回是一种风格选择)
-
@SrikanthVenugopalan 感谢您提供的链接,尽管我不太关心隐式与显式返回的性能因素。相反,我更关心 ruby 中是否存在隐式返回的实际用例——如果有,我的示例是否是其中之一。
-
当您甚至不使用生成的
words_array时,为什么还要使用map而不是each?