0

I have the following code in Ruby:

class Base
  def Function1
    puts 'Base Function1'
  end

  def Function2
    Function1
  end
end

class Derived < Base
  def Function1
    puts 'Derived Function1'
  end
end

obj = Derived.new
obj.Function2

When I run the above code, I get the following error:

/Users/vkuppuswamy/.rvm/rubies/ruby-2.0.0-p0/bin/ruby -e $stdout.sync=true;$stderr.sync=true;load($0=ARGV.shift) /Users/vkuppuswamy/RubymineProjects/TestRubyProj/TestRuby.rb
/Users/vkuppuswamy/RubymineProjects/TestRubyProj/TestRuby.rb:7:in `Function2': uninitialized constant Base::Function1 (NameError)
    from /Users/vkuppuswamy/RubymineProjects/TestRubyProj/TestRuby.rb:18:in `<top (required)>'
    from -e:1:in `load'
    from -e:1:in `<main>'

I can see that the in Function2 in class Base, an attempt has been made to call some constant Function1. I do not see why this would happen. I thought the derived class Function1 method will be invoked. When I change the Function2 in the base class to:

  def Function2
    self.Function1
  end

where I invoke Function1 using self, it works, and I get in output:

Derived Function1

Can you please help me understand why this is happening. I thought the self was implicit in Ruby.

1
  • 5
    Conventions in Ruby are that Constants start with a Capital letter, while methods are lowercase. Try calling your functions function1 etc. What happens? Commented Jun 13, 2013 at 7:19

1 Answer 1

5

Constants (this includes classes) are written in UpperCase, methods/functions are written in lowercase. This has nothing to do with inheritance, consider:

def Foo
  puts 'Foo'
end

Foo
# NameError: uninitialized constant Foo

This happens because when Ruby sees an uppercase token, it looks for a constant and that's it. You could explicitly tell Ruby to look for a method by using parentheses () but just don't do it:

Foo()
# Foo

Use lowercase method names instead. Then, your code will work as expected:

class Base
  def function1
    puts 'Base function1'
  end

  def function2
    function1
  end
end

class Derived < Base
  def function1
    puts 'Derived function1'
  end
end

obj = Derived.new
obj.function2

This prints

Derived function1
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.