Heads up: This description was created by AI and might not be 100% accurate.
to_array.rb
This Ruby code snippet demonstrates reading data from an Excel file (‘book.xlsx’) using the roo
gem. It initializes an empty two-dimensional array (two_dimensional
) and then reads each row from the sheet named ‘mysheet’ into this array. Finally, it prints the populated two_dimensional
array, which contains the data from the Excel sheet.
Additional Note
This Ruby script utilizes the roo
library to read data from an Excel file and store it in a two-dimensional array. Here’s what it does:
- Require ‘roo’:
- This line imports the
roo
library into your Ruby script, enabling you to work with Excel files.
- This line imports the
- Initialize an Empty Array:
two_dimensional = []
: This line initializes an empty array calledtwo_dimensional
, which will store the data read from the Excel sheet.
- Open Excel File and Select Sheet:
xlsx = Roo::Excelx.new('./book.xlsx')
: This line creates a new instance ofRoo::Excelx
, specifying the Excel filebook.xlsx
to work with.sh1 = xlsx.sheet('mysheet')
: This line selects a specific sheet named'mysheet'
from the Excel file and assigns it to the variablesh1
.
- Iterate Through Each Row:
sh1.each do |row|
: This loop iterates through each row in the selected sheet ('mysheet'
).two_dimensional << row
: Within the loop, each row is appended to thetwo_dimensional
array, effectively creating a two-dimensional array where each element represents a row in the Excel sheet.
- Return the Two-Dimensional Array:
two_dimensional
: Finally, the script returns the two-dimensional array containing the data read from the Excel sheet.
This script provides a straightforward way to read data from an Excel file into a two-dimensional array in Ruby, making it accessible for further processing or manipulation within your script.
Ruby code snippet
require 'roo'
#=> true
two_dimensional = []
#=> []
xlsx = Roo::Excelx.new('input/roo/book.xlsx')
#=>
<#Roo::Excelx:2350 @tmpdir @shared @filename @sheet_files @sheet_names @sheets @...
sh1 = xlsx.sheet('mysheet')
#=>
<#Roo::Excelx:2350 @tmpdir @shared @filename @sheet_files @sheet_names @sheets @...
sh1.each do |row|
two_dimensional << row
end
#=> 1
two_dimensional
#=>
[["key", "value"],
[1.0, "a"],
[2.0, "b"],
[3.0, "c"],
[4.0, "d"],
[5.0, "e"],
[6.0, "f"]]
Executed with Ruby 3.4.5
.