Ruby中的继承方案

Ven*_*k K 0 ruby oop

我在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
Run Code Online (Sandbox Code Playgroud)

当我运行上面的代码时,我收到以下错误:

/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>'
Run Code Online (Sandbox Code Playgroud)

我可以看到,Function2在课堂上Base,已经尝试调用一些常量Function1.我不明白为什么会这样.我以为Function1将调用派生类方法.当我Function2将基类更改为:

  def Function2
    self.Function1
  end
Run Code Online (Sandbox Code Playgroud)

在那里我调用Function1使用self,它的工作原理,我在输出得到:

Derived Function1
Run Code Online (Sandbox Code Playgroud)

你能帮我理解为什么会这样吗?我以为这self是隐含在Ruby中的.

Pat*_*ity 5

class写入常量(包括es),编写UpperCase方法/函数lowercase.这与继承无关,请考虑:

def Foo
  puts 'Foo'
end

Foo
# NameError: uninitialized constant Foo
Run Code Online (Sandbox Code Playgroud)

发生这种情况是因为当Ruby看到一个大写的标记时,它会查找一个常量,就是这样.您可以明确告诉Ruby使用括号查找方法,()不要这样做:

Foo()
# Foo
Run Code Online (Sandbox Code Playgroud)

请改用小写方法名称.然后,您的代码将按预期工作:

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
Run Code Online (Sandbox Code Playgroud)

这打印

Derived function1
Run Code Online (Sandbox Code Playgroud)