Ruby实用小脚本

Mar 16, 2015


### 1.Ruby正则中文汉字

1.puts /[一-龥]+/.match(“this is 中文”) =>中文
2.str2=”123中文”
puts /\p{Han}+/u.match(str2) # /u是utf-8
/a/.encoding # US-ASCII
/a/u.encoding # UTF-8
Ruby和部分语言可以直接 #{Han} 等方式匹配特定的语言,但是对于某些语言,如JavaScript,是不可能如此简便的。
还有常用的: /\p{Word}+/u 不限于 a-z0-9 的成词字符(就是非标点制表符空格等杂类的字符) /\p{Hiragana,Katakana}+/u 匹配平假名+片假名 还有一篇讨论:https://ruby-china.org/topics/5680

2.Ruby遍历文件夹

原先需要自己手写一个递归算法:

def traverse_dir(file_path)
    if File.directory? file_path
        Dir.foreach(file_path) do |file|
            if file !="." and file !=".."
                traverse_dir(file_path+"/"+file)
            end
        end
    else
        puts "File:#{File.basename(file_path)}, Size:#{File.size(file_path)}"
    end
end

而今Ruby已经提供了一个Find.find方法,封装的更好,可以直接按照下面的例子使用:


require 'find'

Find.find('/Users/happy') do |path|
  puts path
end

3.Ruby读写excel

0.读取本地文件两个方法:

	file = open(path)
	lines = file.readlines
	lines.each do |line|
		p line
	end

	file = File.open(filePath, "r")
	file.each_line do |line| 
		p line
	end

方法区别:前者会出现双引号和换行符。
1.读。读取excel可以用:roo=>Github官网, roo官网stackoverflow上的一个提问
值得注意的是如果读取的是xls文件而不是xlsx文件,那么需要gem install roo-xls。open文件时指定类型,如下操作:

require 'roo'
require 'roo-xls'

xlsx = Roo::Spreadsheet.open('/Users/h/Documents/rubyProject/刘亦菲.xls',extension: :xls)
puts xlsx.sheet(0).cell('B',2)

2.写。写excel推荐用spreadsheet插件
安装方式:gem install spreadsheet
Excel文件生成写入数据实例:

require ‘rubygems’  
require ‘spreadsheet/excel’  
#先加载spreadsheet类库,然后,指定编码接着,就可以创建一个Workbook了  
book = Spreadsheet::Workbook.new
#创建表单:
sheet1 = book.create_worksheet
sheet1.name = ‘My First Worksheet’
#或直接指定名字创建表单:
sheet2 = book.create_worksheet :name => ‘My Second Worksheet’
那么,这时我们可以采用如下方式加载数据到表单Worksheet#[]=,
Worksheet#update_row,
或者直接给一个指定单元格复制
sheet1.row(0).concat %w{Name Country Acknowlegement}
sheet1[1,0] = ‘Japan’
row = sheet1.row(1)
row.push ‘Creator of Ruby’
row.unshift ‘Yukihiro Matsumoto’
sheet1.row(2).replace [ 'Daniel J. Berger', 'U.S.A.',
'Author of original code for Spreadsheet::Excel' ]
sheet1.row(3).push ‘Charles Lowe’, ‘Author of the ruby-ole Library’
sheet1.row(3).insert 1, ‘Unknown’
sheet1.update_row 4, ‘Hannes Wyss’, ‘Switzerland’, ‘Author’
#对输出格式做处理
sheet1.row(0).height = 18
format = Spreadsheet::Format.new :color => :blue,
:weight => :bold,
:size => 18
sheet1.row(0).default_format = format
bold = Spreadsheet::Format.new :weight => :bold
4.times do |x| sheet1.row(x + 1).set_format(0, bold) end
#保存excel文件
book.write ‘excel-file.xls’

替换文件中的字符串:

# load the file as a string
data = File.read("hello.txt") 
# globally substitute "install" for "latest"
filtered_data = data.gsub("install", "latest") 
# open the file for writing
File.open("hello.txt", "w") do |f|
  f.write(filtered_data)
end

Or you can make it a one liner:

File.write("hello.txt",File.open("hello.txt",&:read).gsub("install","latest"))