user3408293
user3408293

Reputation: 1395

Extra expression in method definition

In this example, the last english in the method definition seems to be unnecessary to me. I took it out and the code worked just as fine. Why does the book include it? Is there some sort of convention I am unaware of?

class Integer
  def to_eng
    if self == 5
      english = 'five'
    else
      english = 'fifty-eight'
    end
    english  
  end
end

#  I'd better test on a couple of numbers...
puts 5.to_eng
puts 58.to_eng

Upvotes: 2

Views: 65

Answers (3)

Amadan
Amadan

Reputation: 198314

The best reason for me is debuggability. In the showcased code, you can insert a debug statement just before the return, and know the result:

class Integer

  def to_eng
    if self == 5
      english = 'five'
    else
      english = 'fifty-eight'
    end

    debugger
    # or: puts "ENGLISH IS #{english}"
    # or: binding.pry
    # or whatever else you want

    english  
  end

end

You can't do that if you leave off the last english, because the return value would change.

Upvotes: 2

dostu
dostu

Reputation: 1518

In ruby, the result of the last statement is always returned from the function. In this case the result is the value of the 'english' variable. However if we remove the last line of the method it still behaves the same because both lines returns the value that is set on 'english' variable.

english = 'five' #=> 'five'
english = 'fifty-eight' #=> 'fifty-eight'

Also this method could be written in more compact and elegant way using a ternary operator.

class Integer
  def to_eng
    self == 5 ? 'five' : 'fifty-eight'
  end
end

Upvotes: 2

SteveTurczyn
SteveTurczyn

Reputation: 36860

It ensures that the value in local variable 'english' is returned. The last executed statement in a method is what's returned.

In this case, it's not needed, but if (for example) the method was rewritten as...

def to_eng
  english = 'fifty-eight'
  english = 'five' if self == 5
end

... you would find that nothing gets returned for any number other than 5 because the last statement... not being executed... would just return nil.

Upvotes: 0

Related Questions