Excel をもっと Ruby らしく使いたい
Excel のワークシート名をまとめて取ろうと思った。
require 'win32ole' excel = WIN32OLE.new 'Excel.Applicatin' at_exit{excel.Quit} book = excel.Workbooks.Open 'sample.xls' book.Sheets.map(&:Name) # ~> -:10:in `method_missing': unknown property or method: `map' (WIN32OLERuntimeError)
map なんて知らんと怒られた。
sheets = book.Sheets sheets.each do |sheet| puts sheet.Name end # >> Sheet1 # >> Sheet2 # >> Sheet3
each はあるのになぁ。
だったら Enumerable か。
sheets.extend Enumerable sheets.map(&:Name) # => ["Sheets1", "Sheets2", "Sheets3"]
できた。
でも、いちいち extend するのが面倒。
オープンクラスの恩恵を受けたい。
sheets.class # => WIN32OLE え? book.class # => WIN32OLE え? excel.class # => WIN32OLE え?なんと、全部 WIN32OLE のインスタンスなのか。
class WIN32OLE include Enumerable end book.Sheets.map(&:Name) # => ["Sheets1", "Sheets2", "Sheets3"]できた。 こんなことして大丈夫なんだろうか。