写了不少的小脚本 cms到一小段文件或者文本处理 都写过

写rb时候才开始注意到 平时不好的习惯 --- 引号的使用

一段例子代码

#writted by mot
class Textcut
 
  def initialize(path)
    @path = path
    @file = @path.split('\').last.split(".").first
    @dir = @path.sub(@file+".txt","")
    @fpath = @path.sub(@file+'.txt','')+'cut\'
    puts "Instance finished"
  end
 
  def debug
    puts "@fpath = " + @fpath
    puts "@path = " + @path
    puts "@dir = " + @dir
    puts "@file = " + @file
    
  end
 
  def cut(num)
    Dir.mkdir(@fpath) unless Dir.exist?(@fpath)
    @fc = 0
    @counter = 0
    f = File.open(@fpath+@file+@fc.to_s+".txt","w+")
    text = File.open(@path).readlines
    size = text.length / num
    text.each do
      |block|
      @counter += 1
      f.puts block
      if(@counter%size == 0)
      @fc += 1
      f.close
      f = File.open(@fpath+@file+@fc.to_s+".txt","w+")
    end
    end
  end
end
#puts "enter  the  file:"
#path = gets
#puts "how much you want to cut"
#size = gets
path = 'C:\Users\Administrator\Desktop\a.txt'
f = Textcut.new(path)
f.debug
f.cut(10)

之前的习惯是这样的

@file = @path.split("\\").last.split(".").first

path = "C:\\Users\\Administrator\\Desktop\\a.txt"

双引号 会翻译 \的转义字符部分跟替换字符串中的变量(ruby php跟perl都是这样的)

习惯于写""  所以每次遇到代码中的路径问题 总会写上 "" 但是命令行下 Argv参数 用户输入总会习惯性输入c:\aa\aa\这种格式的路径

翻译成字符串就是 c:aaaa 啊哈 悲剧了 ?这个算什么路径

所以对于路径的处理 最好习惯用 ' '

 posted on 2012-03-13 19:05  吴家耀  阅读(236)  评论(0)    收藏  举报