views:

84

answers:

2

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?

A: 

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_

Michael Kohl
A: 

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.

Mladen Jablanović
Thank you. I did not know you could write class definitions over multiple declarations like that. Ruby is great!
doctororange