【问题标题】:How to include/require/load a file in ruby with instance variables如何使用实例变量在 ruby​​ 中包含/要求/加载文件
【发布时间】:2010-03-13 09:29:56
【问题描述】:

我想把一个大的变量定义放在一个单独的文件中,以便让它不碍事。不过我一定是做错了什么,因为我的puts 电话没有发出任何声音。

my_class.rb:

class foobar
  def initialize
    require 'datafile.rb'
    puts @fat_data
  end
end

数据文件.rb:

@fat_data = [1,2,3,4,5,6,7,8,9,10]

你可以这样使用require吗?

【问题讨论】:

    标签: ruby require instance-variables


    【解决方案1】:

    你可以这样做:

    my_class.rb:

    class Foobar
      def initialize
        init_fat_data
        puts @fat_data
      end
    end
    

    数据文件.rb:

    class Foobar
      private
    
      def init_fat_data
        @fat_data = [1,2,3,4,5,6,7,8,9,10]
      end
    end
    

    或者,也许,将datafile.rb 中的class Foobar 更改为module MyData,然后将模块包含到my_class.rb 中的Foobar 类中。

    【讨论】:

    • 谢谢。我不知道您可以在这样的多个声明上编写类定义。红宝石很棒!
    【解决方案2】:

    如果你只是想从类定义中获取数据,你也可以使用 __END__ 和 DATA:

    Useless Ruby Tricks: DATA and __END__

    【讨论】:

      猜你喜欢
      • 2012-12-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-17
      • 2014-02-01
      • 2010-09-14
      • 2011-11-25
      相关资源
      最近更新 更多