Conditional methods

699 views

What is the return value of the following Ruby code?

class Greeting
  def self.hello = "hello" if false
end

Greeting.hello # => ???

The correct answer is

nil

"hello"

It raises SyntaxError

It raises NoMethodError

Unlock Your Ruby Potential

Subscribe to RubyCademy and get free access to all our courses, plus hundreds of fun Ruby cards, quizzes, guides, and tutorials!

Explanation

def self.hello = "hello" if false

is interpreted as

(def self.hello = "hello") if false

So as the if-statement is falsey then (def self.hello = "hello") is never executed and Greeting.hello is never created.

Unlock Your Ruby Potential

Subscribe to RubyCademy and get free access to all our courses, plus hundreds of fun Ruby cards, quizzes, guides, and tutorials!

RubyCademy ©