依然是《Ruby基础教程》中的例子,这回程序需要根据输入的参数进行处理,我们在用irb命令的时候,直接在程序文件名后面加上参数就可以了,那么假如要使用Rubymine等IDE的时候呢?
pattern = Regexp.new(ARGV[0])
filename = ARGV[1]
File.open(filename) do |file|
file.each_line do |line|
if pattern =~ line
print line
end
end
end
其实IDE肯定要比写命令高效和准确的,只需按照下面这样设置就可以了。
然后进入到运行和Debug参数设置页面,如下进行设置。
我们在设置完成之后发现还是会报错,原因是参数中的日文编码是GBK的,而我们程序中的文字编码是UTF-8的,所以对程序中接收到的参数使用encode方法进行编码转换之后就可以正常进行了。修改之后我的程序是这样的:
Encoding.default_external = Encoding.find('utf-8')
pattern = Regexp.new(ARGV[0].to_s.encode('utf-8'))
filename = ARGV[1]
countS = 0
File.open(filename) do |file|
file.each_line do |line|
if pattern =~ line
print line
countS += 1
end
end
end
print "含有" << ARGV[0].to_s.encode('utf-8') << "的行数为:" << countS.to_s
当然还有一些可以完善的地方,欢迎大家拍砖。