Search code examples
rubyreturnblock

Ruby Block statements and Implicit Returns


I always thought that rubyists choose to make returns in ruby implicit because of a style preference (less words = more concise). However, can someone confirm with me that in the following example you actually have to make the returns implicit or else the intended functionality won't work? (The intended functionality is to be able to split a sentence into words and return either "Begins with a vowel" or "Begins with a consonant" for each word)

# 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

Now, I know there are definitely many ways to make this code more efficient and better, but the reason I've laid it out like this is to illustrate the need for the implicit returns. Can someone confirm with me that implicit returns are indeed needed and not just a stylistic choice?

EDIT: Here's an example to illustrate what I'm trying to show:

# 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" 

Solution

  • The implicit return value of a method is the last expression evaluated in the method.

    In your case, neither of the two lines you annotated are the last expression. The last expression that gets evaluated is the assignment to words_array (which BTW is completely useless since because it is the last expression there is no way to use that variable afterwards).

    Now, what is the value of an assignment expression? It is the value being assigned, in this particular case, the return value of the map method, which is an Array. So, that is what the method returns.

    In the second example, at the very first iteration of the map, you will hit one of the two returns and thus immediately return from the method. In the first example, however, you will always iterate through the entire words array.

    The problem is not that implicit and explicit returns are different, the problem is that the two lines you claim are implicit returns aren't.