My class name conflicting with Ruby's

2020-04-11 06:45发布

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"?

3条回答
小情绪 Triste *
2楼-- · 2020-04-11 06:53

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.

查看更多
你好瞎i
3楼-- · 2020-04-11 07:05
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

查看更多
淡お忘
4楼-- · 2020-04-11 07:12

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
查看更多
登录 后发表回答