Ruby block 语句和隐式返回

标签 ruby return block

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

最佳答案

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

在您的例子中,您注释的两行中都没有是最后一个表达式。评估的最后一个表达式是对 words_array 的赋值(顺便说一句,这是完全没用的,因为它是最后一个表达式,之后无法使用该变量)。

现在,赋值表达式的值是多少?它是被分配的值,在这种特殊情况下,是 map 方法的返回值,它是一个 Array。所以,这就是该方法返回的内容。

second 示例中,在 map 的第一次迭代中,您将点击两个 return 之一,因此立即从方法返回。然而,在第一个示例中,您将始终遍历整个 words 数组。

问题是不是隐式和显式返回不同,问题是您声称是隐式返回的两行不是。

关于Ruby block 语句和隐式返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15187287/

相关文章:

ios - Phonegap(iOS): can not return to site after paypal payment

ruby-on-rails - Ruby 结构创建 block 无法访问 block 外的变量

ios - IOS程序中如何使用equalTo方法

arrays - Ruby 可枚举 - 查找最多 n 次匹配元素

arrays - 如何查找从文件中读取的二维数组元素出现的次数?

java - Java中 "return methodA() || methodB()"的用途是什么

javascript - 从 getter 返回后执行一个操作

ruby - block 第一次不识别变量

html - 中间人链接背景图片失败。为什么?

c - Ruby 和 C 之间的主要区别