My class name conflicting with Ruby's

落花浮王杯 提交于 2019-12-02 00:02:37

问题


I have a class in my module that is called "Date". But when i want to utilize the Date class packaged with ruby, it uses my Date class instead.

module Mymod
  class ClassA
    class Date < Mymod::ClassA
      require 'date'

      def initialize
        today = Date.today # get today's date from Ruby's Date class
        puts "Today's date is #{today.to_s}"
      end
    end
  end
end

Mymod::ClassA::Date.new

The ouput from running this is

test.rb:7:in `initialize': undefined method `today' for Mymod::ClassA::Date:Class (NoMethodError)

Is there any way I can reference ruby's Date class from within my own class also called "Date"?


回答1:


def initialize
        today = ::Date.today # get today's date from Ruby's Date class
        puts "Today's date is #{today.to_s}"
      end

What is double colon in Ruby




回答2:


In your code Date implicitly looks for the Date class declaration from within the Date < Mymod::ClassA class scope – this Date declaration does not include the method today.

In order to reference Ruby's core Date class, you'll want to specify that you're looking in the root scope. Do this by prefixing the Date with the :: scope resolution operator:

today = ::Date.today # Resolves to `Date` class in the root scope

However, in truth, you should avoid naming conflicts/collisions when it comes to Ruby core classes. They're named with convention in mind, and it's typically less confusing/more descriptive to name custom classes something other than the same name as a core class.




回答3:


I agree with others that you should change the name of your class, but you could do this:

module Mymod
  require 'date'
  RubyDate = Date
  Date = nil      
  class ClassA
    class Date < Mymod::ClassA
      def initialize
        today = RubyDate.today # get today's date from Ruby's Date class
        puts "Today's date is #{today.to_s}"
      end
    end
  end
end

Mymod::ClassA::Date.new # => Today's date is 2014-01-05


来源:https://stackoverflow.com/questions/20940499/my-class-name-conflicting-with-rubys

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!