Home > Enterprise >  How to override multi dimensional array operator ruby
How to override multi dimensional array operator ruby

Time:11-17

I want to override multi dimensional array operator

worksheet['column1'][1]= 'works' should change worksheet so that in row 1 in 'column1' value is 'works'.

Other things I did with worksheet work so it is not connection problem. Also I get no errors on this but it does not work.

I have tried this:

def self.[]=(col,row,value)
  $ws[col,row] = value
end

I have also tried this:

def self.[]=(*args)
  (col,row,value) = args
  $ws[col,row] = value
end

CodePudding user response:

The statement worksheet['column1'][1]= is actually not one method call, but two. Therefore, to make this work, you need to define two methods.

I would try the following:

# create a new column class
class Column
  def initialize(sheet, column)
    @sheet = sheet
    @column = column
  end

  def []=(row, value)
    @sheet[@column, row] = value
  end
end

# use like this
def self.[](column)
  Column.new($ws, column)
end

The first [] call will return an instance of Column that stores a pointer to the sheet and the column you want to set. The pointer to the sheet is actually not necessary because you work with a global $ws variable. But global variables are usually considered a code smell in Ruby, and therefore I would pass it explicitly to make a refactoring easier in the future.

The second []= call will then be handled by the column instance.

CodePudding user response:

I have soved it. This is the solution:

class Column

def initialize(column)
  @column = column
end

def []=(row, value)
  $ws[row 1,@column] = value
  $ws.save
end
end

def self.[](column)
Column.new(GoogleDrive::Worksheet.find_column_index(column))
end

Answer from here helped me to solve it

  • Related