【问题标题】:Extending hash constant in another file在另一个文件中扩展哈希常量
【发布时间】:2012-07-03 14:43:53
【问题描述】:

我有一颗宝石,其中一个类是相似的:

class Test
    TESTING = {
        :sth1 => 'foo',
        :sth2 => 'bar'
    }

    # p Test.new.show 
    # should print 'cat'
    def show
        p TESTING[:sth3]
    end 

end

我在其他文件中扩展

# in other file
class Test 
    TESTING = {
        :sth3 => 'cat'
    }       
end

但我需要在第一个文件中使用 :sth3,因为代码的第一部分代表。 提前谢谢。

【问题讨论】:

    标签: ruby-on-rails ruby inheritance constants


    【解决方案1】:

    你没有扩展它,你用一个新的哈希替换了它。以下是解决方法:

    # in the other file
    Test::TESTING[:sth3] = 'cat'
    

    我建议使用延迟初始化的方法,以便您可以按任意顺序排列分配:

    class Test
      def self.testing
        @testing ||= {}
      end
    
      testing[:sth1] = 'foo'
      testing[:sth2] = 'bar'
    end
    
    # in the other file
    Test.testing[:sth3] = 'cat'
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-15
      • 2020-02-20
      • 1970-01-01
      • 2014-03-30
      • 2013-08-09
      相关资源
      最近更新 更多