f=File.new(File.join("C:","Test.txt"), "w+")
f.puts("I am Jack")
f.puts("Hello World")
文件模式
"r" :Read-only. Starts at beginning of file (default mode).
"r+" :Read-write. Starts at beginning of file.
"w" :Write-only. Truncates existing file to zero length or creates a new file for writing.
"w+" :Read-write. Truncates existing file to zero length or creates a new file for reading and writing.
"a" :Write-only. Starts at end of file if file existsotherwise, creates a new file for writing.
"a+" :Read-write. Starts at end of file if file existsotherwise, creates a new file for reading and writing.
"b" :(DOS/Windows only.) Binary file mode. May appear with any of the key letters listed above
二、读取文件
file=File.open(File.join("C:","Test.txt"),"r")
file.each { |line| print "#{file.lineno}.", line }
file.close
三、新建、删除、重命名文件
File.new( "books.txt", "w" )
File.rename( "books.txt", "chaps.txt" )
File.delete( "chaps.txt" )
四、目录操作
1 创建目录
Dir.mkdir("c:/testdir")
04 #删除目录
05 Dir.rmdir("c:/testdir")
07 #查询目录里的文件
08 p Dir.entries(File.join("C:","Ruby")).join(' ')
10 #遍历目录
11 Dir.entries(File.join("C:","Ruby")).each {
|e| puts e
}
1、ARGV and ARGF
ARGV
ARGV <<"cnblogslink.txt"
#The gets method is a Kernel method that gets lines from ARGV
print while gets
p ARGV.class
ARGF
while line = ARGF.gets
print line
end
2、文件信息查询
#文件是否存在
p File::exists?( "cnblogslink.txt" ) # =>true
#是否是文件
p File.file?( "cnblogslink.txt" ) # =>true
#是否是目录
p File::directory?( "c:/ruby" ) # =>true
p File::directory?( "cnblogslink.txt" ) # =>false
#文件权限
p File.readable?( "cnblogslink.txt" ) # =>true
p File.writable?( "cnblogslink.txt" ) # =>true
p File.executable?( "cnblogslink.txt" ) # =>false
#是否是零长度
p File.zero?( "cnblogslink.txt" ) # =>false
#文件大小 bytes
p File.size?( "cnblogslink.txt" ) # =>74
p File.size( "cnblogslink.txt" ) # =>74
#文件或文件夹
p File::ftype( "cnblogslink.txt" ) # =>"file"
#文件创建、修改、最后一次存取时间
p File::ctime( "cnblogslink.txt" ) # =>Sat Sep 19 08:05:07 +0800 2009
p File::mtime( "cnblogslink.txt" ) # =>Sat Sep 19 08:06:34 +0800 2009
p File::atime( "cnblogslink.txt" ) # =>Sat Sep 19 08:05:07 +0800 2009
3、查找文件
puts "查找目录下所有文件及文件夹"
Dir["c:/ruby/*"].each {|x|
puts x
}
puts "条件查询"
Dir.foreach('c:/ruby') {
|x| puts x if x != "." &&x != ".."
}
puts "查找某一类型文件"
Dir["*.rb"].each {|x|
puts x
}
puts "Open 查询"
Dir.open('c:/ruby') { |d| d.grep /l/ }.each{|x| puts x}
puts "---------------------------"
puts "正则表达式查询"
Dir["c:/ruby/ruby/[rs]*"].each{|x| puts x}
puts "------------------------"
Dir["c:/ruby/[^s]*"].each{|x| puts x}
puts "------------------------"
Dir["c:/ruby/{ruby,li}*"].each{|x| puts x}
puts "------------------------"
Dir["c:/ruby/?b*"].each{|x| puts x}
puts "查找目录及子目录的文件"
require 'find'
Find.find('./') { |path| puts path }
3、查询目录及子目录文件
require "find"
Find.find("/etc/passwd", "/var/spool/lp1", ".") do |f|
Find.prune if f == "."
puts f
end
原型:ref.find( [ aName ]* ) {| aFileName | block }
prune:Skips the current file or directory, restarting the loop with the next entry. If the current file is a directory, that directory will not be recursively entered. Meaningful only within the block associated with Find::find.
4、文件比较 复制等
require 'ftools'
File.copy 'testfile', 'testfile1' » true
File.compare 'testfile', 'testfile1' » true
1.Argument ProcessingRuby 使用了 Symbols 和 Hash 来达到虚拟关键字参数(Pseudo-Keyword Arguments)。这种技巧被广泛应用在 Ruby 的函式库和 Rails 中,增加了阅读性,也很容易使用。
def blah(options)
puts options[:foo]
puts options[:bar]
end
blah(:foo =>"test", :bar =>"test")
Ruby 也可以将参数列当成阵列使用:
def sum(*args)
puts args[0]
puts args[1]
puts args[2]
puts args[3]
end
sum(1,2,3)
如此就可以设计出不固定参数列、十分弹性的 API。类似於 C++ 的 function overloading。在 Rails 中也十分常见这样的 API 设计,例如 link_to 就支援了两种用法:
# USAGE-1 without block
<% link_to 'Posts list', posts_path, :class =>'posts' %>
# USAGE-2 with block
<% link_to posts_path, :class =>'posts' do %>
Posts list
<% end %>
搭配虚拟关键字参数使用的话,可以参考 ActiveSupport#extract_options! 这个小技巧取出 Hash 值。
2. Code Blocks
程式区块(Block)是 Ruby 最重要的特色,除了拿来做迭代(Iteration)之外,也可以包装前後置处理(pre- and Post-processing),一个最基本的例子就是开档了,一般程序式的写法如下:
f = File.open("myfile.txt", 'w')
f.write("Lorem ipsum dolor sit amet")
f.write("Lorem ipsum dolor sit amet")
f.close
使用 Block 之後,我们可以将 f.close 包装起来,不需要明确呼叫。只要程式区块结束,Ruby 就会自动关档。程式一来因为缩排变得有结构,二来也确定档案一定会关闭(不然就语法错误了)
# using block
File.open("myfile.txt", 'w') do |f|
f.write("Lorem ipsum dolor sit amet")
f.write("Lorem ipsum dolor sit amet")
end
另一个程式区块的技法,是用来当做回呼(Dynamic Callbacks)。在 Ruby 中,程式区块也是物件,於是我们可以将程式区块如透过”注册”的方式先储存下来,之後再依照需求找出来执行。例如在 Sinatra 程式中:
get '/posts' do
#.. show something ..
end
post '/posts' do
#.. create something ..
end
我们”注册”了两个回呼:一是当浏览器送出 GET ‘/posts’ 时,会执行 show something 的程式区块,二是 POST ‘/posts’ 时。
3. Module
模组(Module)是 Ruby 用来解决多重继承问题的设计。其中有一招 Dual interface 值得一提:
module Logger
extend self
def log(message)
$stdout.puts "#{message} at #{Time.now}"
end
end
Logger.log("test") # as Logger’s class method
class MyClass
include Logger
end
MyClass.new.log("test") # as MyClass’s instance method
Ruby 的 extend 作用是将模组混入(mix-in)进单件类别(singleton class),於是 log 这个方法除了可以像一般的模组被混入 MyClass 中使用,也可以直接用 Logger.log 呼叫。
要将 Ruby 模组的混入成类别方法(class method),也有一些常见的 pattern 模式,可以将模组设计可以同时混入实例方法(instance method)和类别方法,请参阅投影片范例。这在撰写 Rails plugin 时非常常用。
4. method_missing?
Ruby 的 Missing 方法是当你呼叫一个不存在的方法时,Ruby 仍然有办法处理。它会改呼叫 method_missing 这个方法,并把这个不存在的方法名称传进去当做参数。这个技巧在 Rails 的 ActiveRecord 中拿来使用:
class Person <ActiveRecord::Base
end
p1 = Person.find_by_name("ihower")
p2 = Person.find_by_name_and_email("ihower", "[email protected]")
其中 find_by_name 和 find_by_email 就是这样的方法。不过这个技巧不是万能丹,它的执行效率并不好,所以只适合用在你没办法预先知道方法名称的情况下。不过也不是没有补救之道,如果同样的方法还会继续呼叫到,你可以在 method_missing 之中用 define_method 或 class_eval 动态定义此方法,那麼下次呼叫就不会进来 method_missing,进而获得效能的改善。事实上,ActiveRecord::Base 的 method_missing 就是这麼做的。(感谢 BigCat 留言提醒我有此补救之道)
另一个 Missing 方法的绝妙 API 设计,是拿来构建 XML 文件:
builder = Builder::XmlMarkup.new(:target=>STDOUT, :indent=>2)
builder.person do |b|
b.name("Jim")
b.phone("555-1234")
b.address("Taipei, Taiwan")
end
# <person>
# <name>Jim</name>
# <phone>555-1234</phone>
# <address>Taipei, Taiwan</address>
# </person>
搭配了区块功能,就能用 Ruby 语法来写 XML,非常厉害。
5. const_missing
除了 method_missing,Ruby 也有 const_missing。顾名思义就是找不到此常数时,会呼叫一个叫做 const_missing 的方法。现实中的例子有 Rails 的 ActiveSupport::Dependencies,它帮助我们不需要先载入所有类别档案,而是当 Rails 碰到一个还不认识的常数时,它会自动根据惯例,找到该档案载入。
我们也可以利用这个技巧,针对特定的常数规则来处理。例如以下的程式会自动将 U 开头的常数,自动转译成 Unicode 码:
class Module
original_c_m = instance_method(:const_missing)
define_method(:const_missing) do |name|
if name.to_s =~ /^U([0-9a-fA-F]{4})$/
[$1.to_i(16)].pack("U*")
else
original_c_m.bind(self).call(name)
end
end
end
puts U0123 # ģ
puts U9999 # 香
6. Methods chaining
方法串接是一个很常见的 API 设计,透过将方法的回传值设成 self,我们就可以串接起来。例如:
[1,1,2,3,3,4,5].uniq!.reject!{ |i| i%2 == 0 }.reverse
# 5,3,1
7. Core extension
Ruby 的类别是开放的,可以随时打开它新增一点程式或是修改。即使是核心类别如 Fixnum 或是 Object(这是所有类别的父类别) 都一样。例如 Rails 就定义了一些时间方法在 Fixnum 里:
class Fixnum
def hours
self * 3600 # 一小时有多少秒
end
alias hour hours
end
Time.now + 14.hours
Ruby 的物件模型与元编程(Meta-programming)
在 Ruby 中,所有东西都是物件。甚至包括类别(class)本身也是物件。这个类别物件(class object)是一个叫做 Class 的类别所实例出来的物件。而所有的物件(当然也包括类别物件),都有一个 metaclass (又叫做 singleton, eigenclass, ghost class, virtual class 等名字)。定义在 metaclass 里的方法,只有该物件能够使用,也就是 singleton method (单件方法),只有该物件才有的方法。
了解什麼是 metaclass 是 Ruby 元编程的一个重要前提知识。Ruby 元编程最常用的用途,就是因应需求可以动态地定义方法,例如在 Rails ActiveRecord 中常见的 Class Macro 应用。
要能随心所欲动态定义方法的关键重点,就是 variable scope (变数的作用域) 了。例如以下我们透过 class_eval 和 define_method 帮 String 定义了一个 say 方法,注意到整个 variable scope 都是通透的,没有建立新的 scope:
name = "say"
var = "it’s awesome"
String.class_eval do
define_method(name) do
puts var
end
end
"ihower".say # it’s awesome
class_eval 可以让我们改变 method definition 区域(又叫做 current class)。除了本投影片,建议可以阅读 Metaprogramming in Ruby: It’s Allhe Self 和 Three implicit contexts in Ruby 这两篇文章深入了解 self 和 current class。
8. Class Macro (Ruby’s declarative style)
Class Macro 是 Ruby Meta-programming 非常重要的一个应用,例如在 Rails ActiveRecord 中:
class User <ActiveRecord::Base
validates_presence_of :login
validates_length_of :login,:within =>3..40
validates_presence_of :email
belongs_to :group
has_many :posts
end