开发者

How to include/require/load a file in ruby with instance variables

开发者 https://www.devze.com 2022-12-22 16:22 出处:网络
开发者_StackOverflow中文版I would like to put a large variable definition in a separate file for the sake of getting it out of the way. I must be doing something wrong though, because my puts call isn

开发者_StackOverflow中文版I would like to put a large variable definition in a separate file for the sake of getting it out of the way. I must be doing something wrong though, because my puts call isn't putting anything out.

my_class.rb:

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

datafile.rb:

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

Can you use require this way?


You can do something like this:

my_class.rb:

class Foobar
  def initialize
    init_fat_data
    puts @fat_data
  end
end

datafile.rb:

class Foobar
  private

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

Or, perhaps, change class Foobar in datafile.rb to module MyData and then include the module to Foobar class in my_class.rb.


If you just want to get the data out of the class definition, you could also use __END__ and DATA:

Useless Ruby Tricks: DATA and __END__

0

精彩评论

暂无评论...
验证码 换一张
取 消