Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

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__

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top