Class: MyMatrix

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/mymatrix.rb,
lib/mymatrix/version.rb

Constant Summary collapse

SEPARATOR =

to_t()の際のセパレータ。

"\t"
VERSION =
"0.1.6"

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(file = nil, opts = {}) ⇒ MyMatrix

コンストラクタ

Args

file

オープンするファイル。

Return

生成されたMyMatrixオブジェクト



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/mymatrix.rb', line 30

def initialize(file=nil, opts={})
	#内部改行コード。
	@internal_lf = '<br>'
	rnd = rand(9999)
	i = 0
	begin
		@log = Logger.new("MyMatrix_ERR_#{i}.log")
	rescue
		i += 1
		retry
	end
	@log.level = Logger::DEBUG
   if(FileIO.filesystem == 's')
     @file  = MyMatrix.toutf8(file.to_s)
   else
     @file  = file
	end

   @mx = LoaderFactory.load(@file, opts)


	@headers = @mx.shift
	registerMatrix
	return self
end

Instance Attribute Details

#fileObject

Returns the value of attribute file.



20
21
22
# File 'lib/mymatrix.rb', line 20

def file
  @file
end

#internal_lfObject

Returns the value of attribute internal_lf.



20
21
22
# File 'lib/mymatrix.rb', line 20

def internal_lf
  @internal_lf
end

#mxObject

Returns the value of attribute mx.



20
21
22
# File 'lib/mymatrix.rb', line 20

def mx
  @mx
end

Class Method Details

.cp932ize(str) ⇒ Object

CP932範囲外の文字コードを変換する関数。ruby1.9の正規表現(鬼車)のため、1.8では使えない。



988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
# File 'lib/mymatrix.rb', line 988

def self.cp932ize(str)
	out = str.dup
	cases = [
            #['−', '―'], #MINUS SIGN(U+2212) to FULLWIDTH HYPHEN-MINUS(U+2015)(windows)
            #↑仕様としては上記が正しいが、運用上MINUS SIGN(U+2212) は FULLWIDTH HYPHEN-MINUS(U+FF0D)に変換する
            #キー入力時にMacとWindowsで同じ文字コードとなることが望ましいため。
            
            ['',''], #WAVE DASH (U+301C) to FULLWIDTH TILDE(U+FF5E)(windows)
            ['',''], #DOUBLE VERTICAL LINE (U+2016, "‖") を PARALLEL TO (U+2225, "∥") に
            ['', ''], #EM DASH (U+2014, "—") を HORIZONTAL BAR (U+2015, "―") に
            #以下、キー入力を想定した変換。
            ['', ''], #MacのハイフンF7(google ime)→Windows(googleime):同じ
            ['', ''], #MacのハイフンF8(google ime)→Windows(googleime):同じ
            ['', ''], #MacのハイフンF9[−](google ime)→Windows[-](googleime):違う。MINUS SIGN(U+2212) to FULLWIDTH HYPHEN-MINUS(U+FF0D)
            ['-', '-'], #MacのハイフンF10(google ime)→Windows(googleime):同じ
            #ユニコード固有文字:ノーブレークスペース
            ['[\u00A0]', ' '],
            #yen
            ['[\u00A5]', ''],
            # éとè:eの上に´と`
            ['[\u00E9]', 'e'],['[\u00E8]', 'e'],
            # todo:よく使う文字(http://www.geocities.jp/laut6/mojibakesetumei/mojibakesetumei2.html より)

            #spaces
            ['[\u2000]', ' '],['[\u2001]', ' '],['[\u2002]', ' '],['[\u2003]', ' '],['[\u2004]', ' '],['[\u2005]', ' '],['[\u2006]', ' '],['[\u2007]', ' '],['[\u2008]', ' '],['[\u2009]', ' '],['[\u200A]', ' '],['[\u205F]', ' '],
            
            #Japanese Addresses
            ['鵢崎', 'みさ崎'],
            ['', ''],
            ['', '']

           ]
   
   
	cases.each do |c|
		out.gsub!(/#{c[0]}/, c[1])
	end
	return out
end

.make_path(path, opts = { }) ⇒ Object



1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
# File 'lib/mymatrix.rb', line 1079

def self.make_path(path, opts={ })
  # opath = makepath(@file, {:ext=>nil, :postfix=>postfix})
dir = File.dirname(path)
  ext = opts[:ext]
ext ||= File.extname(path)
  postfix = opts[:postfix].to_s

basename = File.basename(path, ".*")
opath = (FileIO.encodePath("#{dir}/#{basename}_#{postfix}#{ext}"))
end

.tosjis(str) ⇒ Object

Args

str

UTF8文字列

Return

CP932の文字列



61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
# File 'lib/mymatrix.rb', line 61

def self.tosjis(str)
	if(RUBY_VERSION =~ /1\.[^9]/)
		#-xは半角カナを全角にするのを抑止するオプション。
		out = NKF.nkf('-W -x -s --cp932', str)
	else
     str = MyMatrix.cp932ize(str)
     begin
       out = str.encode("Windows-31J")
     rescue => e
       p e
       p str
       out = str
     end
	end
	return out
end

.toutf8(str) ⇒ Object

外部ファイルエンコード(CP932)を内部エンコード(UTF8)に変換する

Args

str

CP932 string

Return

UTF8 String



82
83
84
85
86
87
88
89
90
# File 'lib/mymatrix.rb', line 82

def self.toutf8(str)
   if(RUBY_VERSION =~ /1\.[^9]/)
     #入力がShift-jisであるとする。
     out = NKF.nkf('-S -x -w --cp932', str)
   else
     out = str.encode('UTF-8')
   end
	return out		
end

.toUtf8Mac(str) ⇒ Object

MacOSXのファイルシステムで使われるUTF8-Mac(BOMつきUTF)に変換する



93
94
95
96
# File 'lib/mymatrix.rb', line 93

def self.toUtf8Mac(str)
	out = str
	return out
end

Instance Method Details

#+(other) ⇒ Object

未検証



267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
# File 'lib/mymatrix.rb', line 267

def +(other)
	out = MyipcMatrix.new
	
	othHeaders = other.getHeaders
	selHeaders = getHeaders
	
	selHeaders.each do |header|
		out.addColumn(header, getColumn(header))
	end
	
	othHeaders.each do |header|
		out.addColumn(header, other.getColumn(header))
	end
	
	return out
end

#<<(row) ⇒ Object



287
288
289
# File 'lib/mymatrix.rb', line 287

def <<(row)
	addRow(row)
end

#[](i) ⇒ Object



258
259
260
# File 'lib/mymatrix.rb', line 258

def [](i,j)
	return @mx[i][j]
end

#[]=(key, value) ⇒ Object



314
315
316
# File 'lib/mymatrix.rb', line 314

def []=(key, value)
	@mx[key] = value
end

#addColumn(header, column) ⇒ Object



284
285
286
# File 'lib/mymatrix.rb', line 284

def addColumn(header, column)
	pushColumn(header, column)
end

#addFlg(targetHeader, compareHeader, values, flgValue = '1') ⇒ Object

compareHeaderの値の中に、valuesに書かれた値があったら、targetHeaderにフラグを立てる



724
725
726
727
728
729
730
731
732
733
734
# File 'lib/mymatrix.rb', line 724

def addFlg(targetHeader, compareHeader, values, flgValue='1')
	compares = getColumn(compareHeader)
	values.each do|value|
		i = compares.index(value)
		if(i)
			setValue(@mx[i], targetHeader, flgValue)
		else
			#raise "VALUE NOT FOUND:#{value}"
		end
	end
end

#addHeader(key) ⇒ Object

ヘッダを追加する



582
583
584
# File 'lib/mymatrix.rb', line 582

def addHeader(key)
	addHeaders([key])
end

#addHeaders(aheaders) ⇒ Object

ヘッダを追加する(配列)



575
576
577
578
579
# File 'lib/mymatrix.rb', line 575

def addHeaders(aheaders)
	@headers.concat(aheaders).uniq!
	
	registerMatrix
end

#addRow(row) ⇒ Object



290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
# File 'lib/mymatrix.rb', line 290

def addRow(row)
	if(row.class != Array)
		row = [row]
	end
	row.size.times do |i|
		if(row[i] == nil)
			row[i] = ''
		end
	end
	
	headerSize = getHeaders.size
	rowSize = row.size
	if(headerSize > rowSize)
		(headerSize - rowSize).times do |i|
			row << ''
		end
	elsif(rowSize > headerSize)
		raise("row size error. headerSize:#{headerSize} rowSize:#{rowSize}")
	end
	@mx << row.dup
end

#concat(mx, opt = {}) ⇒ Object



842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
# File 'lib/mymatrix.rb', line 842

def concat(mx, opt={})
	notfoundHeaders = []
	mx.each do |row|
		o = []
		mx.getHeaders.each do |head|
			begin
				self.setValue(o, head, mx.getValue(row, head))
			rescue => e
				#p e
				if(opt[:loose]==true)
					self.addHeaders([head])
					#p "#{head} added"
					retry
				else
					notfoundHeaders << head
				end
			end
		end
		self << o
	end
	if(notfoundHeaders.size > 0)
		raise "notfoundHeader : #{notfoundHeaders.uniq.join(',')}"
	end
	return self
end

#concatCells(headers, colname) ⇒ Object



675
676
677
678
679
680
681
682
683
684
# File 'lib/mymatrix.rb', line 675

def concatCells(headers, colname)
	addHeaders([colname])
	@mx.each do |row|
		val = []
		headers.each do |header|
			val << getValue(row, header)
		end
		setValue(row, colname, val.join('_').gsub(/_+/, '_'))
	end
end

#concatDir(dir) ⇒ Object

フォルダ内ファイルの結合。絶対パスを指定する



874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
# File 'lib/mymatrix.rb', line 874

def concatDir(dir)
	dir = File.expand_path(dir)
	Dir.entries(dir).each do |ent|
		if(ent =~ /^\./)
		else
			#p ent

			file = dir + '/' + ent
			#p "concat:#{file}"
			nmx = MyMatrix.new(file)
			self.concat(nmx)
		end
	end

end

#concatFile(file, opt = {}) ⇒ Object



867
868
869
870
871
872
# File 'lib/mymatrix.rb', line 867

def concatFile(file, opt={})
	#p file
	mx = MyMatrix.new(file)
	self.concat(mx, opt)
	return self
end

#correctCityCodes!(colname = '都道府県市区町村コード') ⇒ Object

都道府県市区町村コードの桁そろえExcelで先頭の0が落ちて桁が変わるため



938
939
940
941
942
943
944
945
946
947
948
949
950
# File 'lib/mymatrix.rb', line 938

def correctCityCodes!(colname = '都道府県市区町村コード')
	self.each do |row|
		code = self.val(row, colname)
		if(code.length == 4)
			self.setValue(row, colname, sprintf("%05d", code))
		elsif(code.length == 5)
			#correct
		else
			raise "Citycode length error. '#{code}'"
		end
	end
	return self
end

#count(header, value) ⇒ Object



785
786
787
788
789
790
791
792
793
794
# File 'lib/mymatrix.rb', line 785

def count(header, value)
	out = 0
	arr = getColumn(header)
	arr.each do |ele|
		if(ele == value)
			out += 1
		end
	end
	return out
end

#countup(header) ⇒ Object

全件カウントして、[value, count] という配列に格納する



796
797
798
799
800
801
802
803
# File 'lib/mymatrix.rb', line 796

def countup(header)
	out = []
	values = getColumn(header).uniq
	values.each do |value|
		out << [value, self.count(header, value)]
	end
	return out
end

#cutOff(head, num) ⇒ Object

num文字以上の項目をnum文字に丸める



1071
1072
1073
1074
1075
1076
1077
1078
# File 'lib/mymatrix.rb', line 1071

def cutOff(head, num)
   self.each do |row|
     v = self.val(row, head)
     if(v =~ /(.{#{num}})/)
       self.setValue(row, head, $1)
     end
   end
end

#delEndSp!Object

末尾空白の削除



953
954
955
956
957
958
959
960
961
962
963
# File 'lib/mymatrix.rb', line 953

def delEndSp!
	self.each do |row|
		self.getHeaders.each do |head|
			val = self.val(row, head)
			if(val =~ /(.*)[  ]$/)
				self.setValue(row, head, $1)
			end
		end
	end
	return self
end

#delete(v) ⇒ Object



619
620
621
# File 'lib/mymatrix.rb', line 619

def delete(v)
	@mx.delete(v)
end

#delete_at(pos) ⇒ Object



608
609
610
# File 'lib/mymatrix.rb', line 608

def delete_at(pos)
	@mx.delete_at(pos)
end

#delete_ifObject

未検証。「要素を順番にブロックに渡して評価し、その結果が真になった要素を すべて削除します。」



613
614
615
616
617
618
# File 'lib/mymatrix.rb', line 613

def delete_if
	out = @mx.delete_if do |row|
		yield(row)
	end
	@mx = out
end

#devide(n) ⇒ Object

n分割した配列を返却する



706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
# File 'lib/mymatrix.rb', line 706

def devide(n)
	out = []
	mx = @mx.dup
	eleSize = mx.size/n
	n.times do |i|
		o = self.empty
		eleSize.times do |j|
			o << mx.shift
		end
		out << o
	end
	#@mx.size%n分余ってるので、追加
	mx.each do |ele|
		out[n-1] << ele
	end
	return out
end

#divide(splitNum) ⇒ Object

複数に分割されたテキストファイルを出力する



353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
# File 'lib/mymatrix.rb', line 353

def divide(splitNum)
	lineNum = (@mx.size / splitNum) + 1
	mymxs = []
	tmp = MyMatrix.new
	tmp.file = @file
	tmp.addHeaders(getHeaders)
	@mx.each_with_index do |row, i|
		tmp << row.dup
		if((i+1) % lineNum == 0)
			mymxs << tmp
			tmp = MyMatrix.new
			tmp.addHeaders(getHeaders)
			tmp.file = @file
		end
	end
	mymxs << tmp
	mymxs.each_with_index do |mymx, i|
		p i
		mymx.to_t_with("#{i}")
	end
end

#dupRow(row, destmx, destrow, headers) ⇒ Object



920
921
922
923
924
925
926
# File 'lib/mymatrix.rb', line 920

def dupRow(row, destmx, destrow, headers)
	headers.each do |head|
		val = self.getValue(row, head)
		destmx.setValue(destrow, head, val)
	end
	return destrow
end

#eachObject



239
240
241
242
243
# File 'lib/mymatrix.rb', line 239

def each
	@mx.each do |row|
		yield(row)
	end
end

#emptyObject

行が空(ヘッダはそのまま)のコピーを返却する



754
755
756
757
758
# File 'lib/mymatrix.rb', line 754

def empty
	out = self.dup
	out.empty!
	return out
end

#empty!Object

selfの行を空にする



761
762
763
764
# File 'lib/mymatrix.rb', line 761

def empty!
	@mx = []
   return self
end

#empty?Boolean

Returns:

  • (Boolean)


1067
1068
1069
# File 'lib/mymatrix.rb', line 1067

def empty?
	@mx.empty?
end

#fill(rows) ⇒ Object



765
766
767
768
769
770
# File 'lib/mymatrix.rb', line 765

def fill(rows)
	rows.each do |row|
		self << row
	end
	return self
end

#filter(header, value) ⇒ Object



812
813
814
815
816
817
818
819
820
821
# File 'lib/mymatrix.rb', line 812

def filter(header, value)
	out = empty
	@mx.each do|row|
		v = getValue(row, header)
		if(v == value)
			out << row
		end
	end
	return out
end

#findObject

ブロックがTrueになる、配列(参照)を返却するメソッド



623
624
625
626
627
628
629
630
631
632
# File 'lib/mymatrix.rb', line 623

def find
	#todo rowsを返却するのと、Mymatrxixを返却するのとどっちがイイのか。。
	rows = []
	@mx.each do |row|
		if(yield(row))
			rows << row.dup
		end
	end
	return rows
end

#firstObject

Arrayっぽく使うためのメソッド。内部の@mx.first



1060
1061
1062
# File 'lib/mymatrix.rb', line 1060

def first
	@mx[0]
end

#flushCol(colname) ⇒ Object

def concat!(mx) o = self.concat(mx) self = o return self end def concatFile!(file) o = self.concatFile(file) self = o return self end



901
902
903
904
905
906
# File 'lib/mymatrix.rb', line 901

def flushCol(colname)
	@mx.each do |row|
		self.setValue(row, colname, '')
	end
	return self
end

#getColumn(colName) ⇒ Object

カラムの値を配列で返却する



147
148
149
150
151
152
153
154
155
156
157
# File 'lib/mymatrix.rb', line 147

def getColumn(colName)
	out = []
	@mx.each do |row|
		begin
			out << getValue(row, colName)
		rescue
			raise "#{colName} notfound: #{row}"
		end
	end
	return out
end

#getColumns(colNames) ⇒ Object

カラムの値を複数指定して、多次元配列を返却するメソッド。



164
165
166
167
168
169
170
# File 'lib/mymatrix.rb', line 164

def getColumns(colNames)
	out = []
	colNames.each do |colName|
		out << getColumn(colName)
	end
	return out
end

#getColumnsByMatrix(colNames) ⇒ Object



173
174
175
176
177
178
179
180
# File 'lib/mymatrix.rb', line 173

def getColumnsByMatrix(colNames)
	out = MyMatrix.new
	colNames.each do |colName|
		col = getColumn(colName)
		out.addColumn(colName, col)
	end
	return out
end

#getCrrValue(row, str) ⇒ Object

MyipcMatrixとの互換性のため。getValueのエイリアス



670
671
672
673
# File 'lib/mymatrix.rb', line 670

def getCrrValue(row, str)
   p 'this class is not MyipcMatrix.'
	getValue(row, str)
end

#getDoubles(arr) ⇒ Object



804
805
806
807
808
809
810
# File 'lib/mymatrix.rb', line 804

def getDoubles(arr)
	doubles = arr.select do |e|
	 arr.index(e) != arr.rindex(e)
	end
	doubles.uniq!
	return doubles
end

#getHeadersObject

ヘッダのコピーを返却する



524
525
526
527
# File 'lib/mymatrix.rb', line 524

def getHeaders
	out = @headers.dup
	return out
end

#getPathObject

読み込んだファイルのパスを返却する



687
688
689
# File 'lib/mymatrix.rb', line 687

def getPath
	return @file
end

#getValue(row, str) ⇒ Object Also known as: val



185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
# File 'lib/mymatrix.rb', line 185

def getValue(row, str)
	out = nil
	index = @headerH[str]
	if(index)
		out = row[index]
		#お尻のセルでNULLの場合などは、nilが返却されてしまう。なので、''となるようにする。
		if(!out)
			out = ''
		end
		#参照を渡さないためdupする
		out = out.dup
	else
		raise "header not found:#{str} file:#{@file}"
	end
	return out
end

#getValues(colName) ⇒ Object

getColumn のエイリアスメソッド



160
161
162
# File 'lib/mymatrix.rb', line 160

def getValues(colName)
	return getColumn(colName)
end

#index(colName, value) ⇒ Object

colNameの値がvalueの行のうち先頭のものを返却する。todo:名称がよくない。



535
536
537
538
539
540
541
542
543
544
545
# File 'lib/mymatrix.rb', line 535

def index(colName, value)
	out = nil
	col = getColumn(colName)
	col.each_with_index do |cell, i|
		if(value == cell)
			out = i
			break
		end
	end
	return out
end

#lastObject

Arrayっぽく使うためのメソッド。内部の@mx.last



1064
1065
1066
# File 'lib/mymatrix.rb', line 1064

def last
	out = @mx[self.size-1]
end

#localEncode(v, enc = 's') ⇒ Object

ファイルの中身をSJISにするために使ってる



375
376
377
378
379
380
381
382
383
384
# File 'lib/mymatrix.rb', line 375

def localEncode(v, enc = 's')
	case enc
	when 'u'
		str = MyMatrix.toutf8(v)
	when 's'
		str = MyMatrix.tosjis(v)
	else
		str = MyMatrix.tosjis(v)
	end
end

#makeHash(fromColName, toColName) ⇒ Object

fromColName => toColNameのハッシュを作成する。fromColNameの値が同じだとtoColNameが上書きされるので使いにくいと思われる。



646
647
648
649
650
651
652
653
654
# File 'lib/mymatrix.rb', line 646

def makeHash(fromColName, toColName)
	out = Hash.new
	@mx.each do |row|
		from = getValue(row, fromColName)
		to = getValue(row, toColName)
		out[from] = to
	end
	return out
end

#makeKey(colname) ⇒ Object

colnameがキーのハッシュを作る。valueはrowの配列。



657
658
659
660
661
662
663
664
665
666
667
# File 'lib/mymatrix.rb', line 657

def makeKey(colname)
	out = {}
	self.each do |row|			
		key = self.val(row, colname)
		if(out[key] == nil)
			out[key] = []
		end
		out[key] << row
	end
	return out
end

#myescape(cell) ⇒ Object



467
468
469
470
471
472
473
474
475
# File 'lib/mymatrix.rb', line 467

def myescape(cell)
	o = cell.to_s.dup
	o.gsub!(/"/, '""')		
	if o =~ /[",']/
		#'
		o = "\"#{o}\""
	end
	return o
end

#popObject



602
603
604
# File 'lib/mymatrix.rb', line 602

def pop
	return @mx.pop
end

#push(var) ⇒ Object



605
606
607
# File 'lib/mymatrix.rb', line 605

def push(var)
	return @mx.push(var)
end

#pushColumn(header, column) ⇒ Object



318
319
320
321
322
323
324
325
326
327
328
# File 'lib/mymatrix.rb', line 318

def pushColumn(header, column)
	colPos = @headers.length
	@headers << header
	registerMatrix
	column.each_with_index do |cell, i|
		if(@mx[i] == nil)
			@mx[i] = []
		end
		@mx[i][colPos] = cell
	end
end

#replaceHeader(before, after) ⇒ Object

ヘッダを置き換える



529
530
531
532
# File 'lib/mymatrix.rb', line 529

def replaceHeader(before, after)
	@headers[@headerH[before]] = after
	registerMatrix
end

#reverseObject

未検証



245
246
247
248
249
250
251
252
# File 'lib/mymatrix.rb', line 245

def reverse
	out = empty
	
	@mx.reverse.each do |row|
		out << row
	end
	return out
end

#search(colName, value) ⇒ Object

colnameの値がvalueの行のrowを配列で返却する。todo:名称がよくない。



560
561
562
563
564
565
566
567
568
569
570
571
572
573
# File 'lib/mymatrix.rb', line 560

def search(colName, value)
	indexes = []
	col = getColumn(colName)
	col.each_with_index do |cell, i|
		if(value == cell)
			indexes << i
		end
	end
	out = self.empty
	indexes.each do |index|
		out << @mx[index]
	end
	return out
end

#searchHeader(str) ⇒ Object

strを含む(/#str/)ヘッダ名を配列で返却する。



696
697
698
699
700
701
702
703
# File 'lib/mymatrix.rb', line 696

def searchHeader(str)
	out = []
	getHeaders.each do |header|
		if(header =~ /#{str}/)
			out << header
		end
	end
end

#searchIndexes(colName, value) ⇒ Object

colnameの値がvalueの行のもののインデックス値を配列で返却する。todo:名称がよくない。



548
549
550
551
552
553
554
555
556
557
# File 'lib/mymatrix.rb', line 548

def searchIndexes(colName, value)
	out = []
	col = getColumn(colName)
	col.each_with_index do |cell, i|
		if(value == cell)
			out << i
		end
	end
	return out
end

#select(headers) ⇒ Object

headersに記載の



635
636
637
638
639
640
641
642
# File 'lib/mymatrix.rb', line 635

def select(headers)
	out = self.class.new
		headers.each do |header|
		out.addColumn(header, getColumn(header))
	end
	out.file = @file
	return out
end

#setPath(path) ⇒ Object

ファイルパスを設定する。 to_tを引数なしで使うと、設定したパスにファイルが生成される。



691
692
693
# File 'lib/mymatrix.rb', line 691

def setPath(path)
	@file = path
end

#setSame(head, headValue, hash) ⇒ Object



927
928
929
930
931
932
933
934
# File 'lib/mymatrix.rb', line 927

def setSame(head, headValue, hash)
	idxs = self.searchIndexes(head, headValue)
	idxs.each do |idx|
		hash.each_pair do |key, value|
			self.setValue(@mx[idx], key, value)
		end
	end		
end

#setValue(row, str, value) ⇒ Object

def getValues(row, arr) out = [] arr.each do |ele| out << getValue(row, ele) end if(out.size == 0) out = nil end return out end



217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
# File 'lib/mymatrix.rb', line 217

def setValue(row, str, value)
	if(!row)
		raise 'row is nil'
	end
	index = @headerH[str]
	if(!index)
		addHeaders([str])
	end
	#参照先の値も変更できるように、破壊メソッドを使う。row[@headerH[str]] = valueでは、参照先が切り替わってしまうので、値の置き換えにならない。
	#findなどで取得したrowに対して処理を行う際に必要な変更。
	if(row[@headerH[str]].class == String)
		row[@headerH[str]].sub!(/^.*$/, value)
	else
		#raise('not string error.')
		#todo 強烈なバグな気もするが、例外を回避し値を代入2010年12月15日
		begin
			row[@headerH[str]] = value.to_s
		rescue
			row[@headerH[str]] = ''
		end
	end
end

#shiftObject



596
597
598
# File 'lib/mymatrix.rb', line 596

def shift
	return @mx.shift
end

#shiftColumnObject



342
343
344
345
346
347
348
349
350
# File 'lib/mymatrix.rb', line 342

def shiftColumn()
	header = @headers.shift
	column = []
	registerMatrix
	@mx.each do |row|
		column << row.shift
	end
	return header, column
end

#sizeObject

行数を返却する



587
588
589
# File 'lib/mymatrix.rb', line 587

def size
	return @mx.size
end

#sortBy(colname, reverse = false) ⇒ Object



907
908
909
910
911
912
913
914
915
916
917
918
919
# File 'lib/mymatrix.rb', line 907

def sortBy(colname, reverse=false)
	sortmx = []
	self.each do |row|
		key = self.getValue(row, colname)
		sortmx << [key, row]
	end
	sortmx.sort!
	self.empty!
	sortmx.each do |keyrow|
		self << keyrow[1]
	end
	return self
end

#to_aryObject

配列と引き算とかする際に使われる。



823
824
825
826
827
828
829
830
# File 'lib/mymatrix.rb', line 823

def to_ary
	arr = []
	@mx.each do |row|
		#arr << row.dup
		arr << row
	end
	return arr
end

#to_csv(outFile = nil, opts = { }) ⇒ Object

CSV出力する。ダブルクオーテーションやカンマをエスケープする。



484
485
486
# File 'lib/mymatrix.rb', line 484

def to_csv(outFile=nil, opts={ })
	to_t(outFile, opts.merge({:separator=>',', :escape=>true}))
end

#to_sObject



831
832
833
834
835
836
837
# File 'lib/mymatrix.rb', line 831

def to_s
	out = ''
	@mx.each do |row|
		out = out + row.to_s + "\n"
	end
	return out
end

#to_s_with_headerObject



838
839
840
841
# File 'lib/mymatrix.rb', line 838

def to_s_with_header
	out = self.getHeaders.to_s + "\n"
	out = out + self.to_s
end

#to_t(outFile = nil, opts = {}) ⇒ Object

テキスト出力する。outFileにxlsが指定された場合は、xls出力する。



414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
# File 'lib/mymatrix.rb', line 414

def to_t(outFile=nil, opts={})
	if(!outFile)
		outFile = @file
	end
	
	#拡張子の判別
	ext = File.extname(outFile).downcase
	case ext
	when '.csv'
		opts[:separator] ||= ','
		opts[:escape] ||= true
	when '.xls'
     to_xls(outFile)
     return
	when '.xlsx'
		p 'use Tab-Separated-Value text format.'
		outFile = outFile + '.txt'
	else
	 #do nothing
	end
	#デフォルトオプションの設定
	opts[:enc] ||= 's'
	opts[:escape] ||= false
	opts[:separator] ||= SEPARATOR
	
	to_text(outFile) do |row|
		orow = []
		if(opts[:escape])
			row.each do |cell|
				orow << myescape(cell)
			end
		else
       row.each do |cell|
  				orow << cell.to_s.gsub(/[#{opts[:separator]}\r\n]/, '')
       end
		end
		
		begin
			str = localEncode(orow.join(opts[:separator]), opts[:enc])
		rescue Encoding::UndefinedConversionError
       orow.each do |ele|
         begin
           localEncode(ele, opts[:enc])
         rescue
           raise "encode error.#{ele}\n(#{orow})"
         end
       end

			@log.debug(row.join(opts[:separator]))
		end
		str
	end
end

#to_t_with(postfix = "out", opts = {}) ⇒ Object

読み込んだファイル名にpostfixを付与してテキストファイル出力する



477
478
479
480
481
# File 'lib/mymatrix.rb', line 477

def to_t_with(postfix="out", opts={})
   opath = MyMatrix.make_path(@file, {:ext=>nil, :postfix=>postfix})
	to_t(opath, opts)
	return opath
end

#to_text(outFile) ⇒ Object

使い方はto_t()を参照。yield。



386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
# File 'lib/mymatrix.rb', line 386

def to_text(outFile)
	outFile = FileIO.encodePath(outFile)
	out = []
	out << @headers
	@mx.each do |row|
		out << row
	end
	begin
		fo = open(outFile, 'wb')
	rescue => e
		p "cannot write file...#{outFile}"
     p e
		sleep(5)
		retry
	end
	out.each_with_index do |row, i|
		if(row == nil)
			warn("line #{i} is nil")
			fo.print("")
		else 
			str = yield(row)
			fo.print(str)
		end
		fo.print("\r\n")
	end
	fo.close
end

#to_xls(outFile = nil, opts = { }) ⇒ Object

xlsにて出力する。



489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
# File 'lib/mymatrix.rb', line 489

def to_xls(outFile=nil, opts={ })
   default_sheet_name = 'Sheet1'
	if(outFile =~ /.xls$/)
	else
		raise "output file is not xls. set .xls file"
	end

   infile =opts[:template]
   inFile ||= self.file

   begin
     xl = Spreadsheet.open(inFile)
     sheet_str = opts[:sheet]
     sheet_str ||= default_sheet_name
     sheet = xl.worksheet(sheet_str)
   rescue
     xl = Spreadsheet::Workbook.new
     sheet = book.create_worksheet
     sheet.name = default_sheet_name
   end

	@headers.each_with_index do |head, i|
		sheet[0, i] = head
	end
	self.each_with_index do |row, i|
     n = i+1 # line number
		row.each_with_index do |cell, j|
			sheet[n, j] = cell
		end
	end
	xl.write(outFile)
end

#twoByteKana!Object

半角カタカナの全角化



965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
# File 'lib/mymatrix.rb', line 965

def twoByteKana!
	self.each do |row|
		self.getHeaders.each do |head|
			val = self.val(row, head)								
			#if(val =~ /[-~]/)
			if(val =~ /[-]/)
				#p "#{self.file} #{val}"
				next
			end
			#nval = Kconv.kconv(val, Kconv::UTF8, Kconv::UTF8)
			#nval = NKF.nkf('-W -w -x --cp932', val)

			nval = NKF.nkf('-W -w', val)

			if(val!=nval)
				#p "#{val}=>#{nval}"
			end
			self.setValue(row, head, nval)
		end
	end
	return self
end

#uniq!Object

未検証。「要素の重複判定は、Object#eql? により行われます。」www.ruby-lang.org/ja/old-man/html/Array.html#uniq



592
593
594
# File 'lib/mymatrix.rb', line 592

def uniq!
	@mx.uniq!
end

#unshift(var) ⇒ Object



599
600
601
# File 'lib/mymatrix.rb', line 599

def unshift(var)
	return @mx.unshift(var)
end

#unShiftColumn(header, column) ⇒ Object

使い勝手が良くないので気をつけて使う(todo参照)



330
331
332
333
334
335
336
337
338
339
340
# File 'lib/mymatrix.rb', line 330

def unShiftColumn(header, column)
	@headers.unshift(header)
	registerMatrix
	column.each_with_index do |cell, i|
		if(@mx[i] == nil)
			@mx[i] = []
		end
		#todo:ヘッダよりでかいrowがある場合バグる。期待していない一番右の値が取れてしまう。
		@mx[i].unshift(cell)
	end
end

#with_serial(headerName = 'No.') ⇒ Object

行番号を付与する



773
774
775
776
777
778
779
780
781
782
# File 'lib/mymatrix.rb', line 773

def with_serial(headerName = 'No.')
	out = self.empty
	out.addHeaders([headerName], 1)
	self.each_with_index do |row, i|
		no = i + 1
		newRow = [no].concat(row)
		out << newRow
	end
	return out
end

#without(regexp_or_string) ⇒ Object



736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
# File 'lib/mymatrix.rb', line 736

def without(regexp_or_string)
   if(regexp_or_string.class == String)
     regexp = /#{regexp_or_string}/
   else
     regexp = regexp_or_string
   end
	newHeaders = []
	@headers.each do |header|
		if(header =~ regexp)
		else
			newHeaders << header
		end
	end
	out = select(newHeaders)
	return out
end