Ruby Block语句和隐式返回

wmo*_*ock 2 ruby return block

我一直认为rubyists因为风格偏好而选择隐藏在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
Run Code Online (Sandbox Code Playgroud)

现在,我知道肯定有很多方法可以使这些代码更有效,更好,但我这样做的原因是为了说明隐含返回的必要性.有人可以向我确认隐含的回报确实需要而不仅仅是一种风格选择吗?

编辑:这是一个例子来说明我想要展示的内容:

# 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" 
Run Code Online (Sandbox Code Playgroud)

Jör*_*tag 5

方法的隐式返回值是方法中计算的最后一个表达式.

在您的情况下,您注释的两行中的任何一行都不是最后一个表达式.得到评估的最后一个表达式是赋值words_array(BTW完全没用,因为它是最后一个表达式,之后无法使用该变量).

现在,赋值表达式的价值是什么?在这种特定情况下,它是指定的值,该map方法的返回值是a Array.所以,这就是方法返回的内容.

第二个示例中,在第一次迭代时map,您将点击两个returns中的一个,从而立即从方法返回.但是,在第一个示例中,您将始终遍历整个words数组.

问题在于隐式和显式返回是不同的,问题是你声称的两行是隐式返回不是.

  • 顺便说一句:你注释的两行*是*暗示`下一个`,即块*的隐式返回值*.如果你在那里放一个明确的`next`,你应该看到没有区别. (2认同)