Class: RubyExcel::Range

Inherits:
Element show all
Defined in:
lib/rubyexcel/element.rb

Overview

A Range of Cells

Instance Attribute Summary

Attributes inherited from Element

#address, #column, #data, #row, #sheet

Instance Method Summary collapse

Methods inherited from Element

#delete, #each, #each_cell, #empty?, #first_cell, #inspect, #last_cell, #map!

Methods included from Address

#address_to_col_index, #address_to_indices, #col_index, #col_letter, #column_id, #expand, #indices_to_address, #multi_array?, #offset, #row_id, #to_range_address

Constructor Details

#initialize(sheet, addr) ⇒ Range

Returns a new instance of Range.



162
163
164
165
# File 'lib/rubyexcel/element.rb', line 162

def initialize( sheet, addr )
  fail ArgumentError, "Invalid Range address: #{ addr }" unless addr =~ /\A[A-Z]{1,3}\d+:[A-Z]{1,3}\d+\z|\A[A-Z]{1,3}:[A-Z]{1,3}\z|\A\d+:\d+\z/
  super
end

Instance Method Details

#to_sObject

The data at address as a TSV String



218
219
220
# File 'lib/rubyexcel/element.rb', line 218

def to_s
  value.map { |ar| ar.map { |v| v.to_s.gsub(/\t|\n|\r/,' ') }.join "\t" }.join($/)
end

#valueArray<Object>

Return the value at this Range’s address

Returns:

  • (Array<Object>)

    the Array of Objects within the data, referenced by the address



173
174
175
# File 'lib/rubyexcel/element.rb', line 173

def value
  expand( address ).map { |ar| ar.map { |addr| data[ addr ] } }
end

#value=(val) ⇒ Object

Set the value at this Range’s address

Parameters:

  • val (Object, Array<Object>)

    the Object or Array of Objects to write into the data



183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
# File 'lib/rubyexcel/element.rb', line 183

def value=( val )

  addresses = expand( address )
  
  # 2D Array of Values
  if multi_array?( val ) && addresses.length > 1
  
    # Check the dimensions
    val_rows, val_cols, range_rows, range_cols = val.length, val.max_by(&:length).length, addresses.length, addresses.max_by(&:length).length
    val_rows == range_rows && val_cols == range_cols or fail ArgumentError, "Dimension mismatch! Value - rows: #{val_rows}, columns: #{ val_cols }. Range - rows: #{ range_rows }, columns: #{ range_cols }"
    
    # Write the values in order
    addresses.each_with_index { |row,idx| row.each_with_index { |el,i| data[el] = val[idx][i] } }
    
  # Array of Values
  elsif val.is_a?( Array )
    
    # Write the values in order
    addresses.flatten.each_with_index { |addr, i| data[addr] = val[i] }
    
  # Single Value
  else
  
    # Write the same value to every cell in the Range
    addresses.each { |ar| ar.each { |addr| data[ addr ] = val } }
    
  end

  val
end