0

Rather than calling cop_log.read_spreadsheet how can I call the method read_spreadsheet directly inside my class when I use ChangeOrderLog.new('path/to/file')?

cop_log.read_spreadsheet populates the @cop_log hash with the data from an excel spreadsheet, is there any way I can populate my hash from within my ChangeOrderLog class instead of outside of it?

require 'creek'

class ChangeOrderLog
  attr_reader :creek, :sheet
  attr_accessor :cop_log
  def initialize(file)
    @creek = Creek::Book.new file
    @sheet= @creek.sheets[0]
    @cop_log = {}
  end
  def read_spreadsheet
    sheet.rows.each { |row| cop_log.merge!(row) }
  end
  def job_number
    return cop_log['G1']
  end
end

cop_log = ChangeOrderLog.new('path/to/file')
cop_log.read_spreadsheet
puts cop_log.job_number
Schwern
  • 153,029
  • 25
  • 195
  • 336
alilland
  • 2,039
  • 1
  • 21
  • 42

2 Answers2

2

The object already exists by the time initialize is called, it just hasn't been initialized yet. So you can call methods in initialize, but do it after the rest of the object has been initialized, especially @sheet.

  def initialize(file)
    @creek = Creek::Book.new file
    @sheet= @creek.sheets[0]
    @cop_log = {}

    read_spreadsheet
  end

read_spreadsheet is shorthand for self.read_spreadsheet. self is the object initialize (or any other method) was called with. In this case self is your freshly created ChangeOrderLog object.

Schwern
  • 153,029
  • 25
  • 195
  • 336
1

You can call methods inside of other methods, initialize is no exception:

def initialize(file)
    @creek = Creek::Book.new file
    @sheet= @creek.sheets[0]
    @cop_log = {}
    read_spreadsheet
end
T. Claverie
  • 11,380
  • 1
  • 17
  • 28