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"?
In your code
Date
implicitly looks for theDate
class declaration from within theDate < Mymod::ClassA
class scope – thisDate
declaration does not include the methodtoday
.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 theDate
with the::
scope resolution operator: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.
What is double colon in Ruby
I agree with others that you should change the name of your class, but you could do this: