我一直认为 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"