Search code examples
rubyscoping

Same method and constant name in Ruby


module Demo  
  Myconstant = 'This is the constant'
  private
    def Myconstant
      puts 'This is the method'
    end
end

class Sample
  include Demo

  def test
    puts Myconstant # => 'This is the constant'
  end

end

Sample.new.test

How does the snippet above work?

Shouldn't Myconstant the method overwrite the "true" constant?

Is there a way to call the method instead?

Thanks.


Solution

  • Use parentheses to explicitly call the method:

    puts Myconstant
    #⇒ 'This is the constant'
    
    puts Myconstant()
    #⇒ 'This is the method'