【问题标题】:My class name conflicting with Ruby's我的班级名称与 Ruby 的冲突
【发布时间】:2016-10-06 13:28:33
【问题描述】:

我的模块中有一个名为“日期”的类。但是当我想使用 ruby​​ 打包的 Date 类时,它会使用我的 Date 类。

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

运行这个的输出是

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

有什么方法可以从我自己的类(也称为“日期”)中引用 ruby​​ 的 Date 类?

【问题讨论】:

  • ::Date 应该会有所帮助。
  • ::Date 是答案,但我建议不要将您的类与通用系统类同名 - 其他人会更难理解您的代码。

标签: ruby class conflict


【解决方案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】:

    在您的代码中,Date 隐式地从Date &lt; Mymod::ClassA 类范围内查找Date 类声明——这个Date 声明不包括方法today

    为了引用 Ruby 的核心 Date 类,您需要指定您正在查看根范围。通过在Date 前加上:: scope resolution operator 来做到这一点:

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

    然而,事实上,当涉及到 Ruby 核心类时,您应该避免命名冲突/冲突。它们的命名考虑到了约定,并且将自定义类命名为 other 通常比与核心类同名更容易混淆/更具描述性。

    【讨论】:

      【解决方案3】:

      我同意其他人的观点,即您应该更改班级名称,但您可以这样做:

      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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-06-18
        • 2018-01-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-12-05
        • 1970-01-01
        相关资源
        最近更新 更多