搞rails也有段时间了,这几天看了一本关于ruby使用技巧的书,发现有很多知识点,自己应该再加强一下,记录一下,总结一下,有一些感觉还是很有意思的
1 定义方法为不可用(不晓得这种情况什么时候去用)
undef 方法名
def a_used_method
p "a used method"
end
irb(main):013:0> a_used_method
"a used method"
irb(main):014:0> undef a_used_method
irb(main):015:0> a_used_method
NameError: undefined local variable or method `a_used_method' for main:Object
from (irb):15
from :0
2 alias 赋予别名
alias :新的方法名 :旧的方法名
3 使用here document 来定义字符串
irb(main):002:0> p <<HEREDOC
irb(main):003:0" this is document
irb(main):004:0" this is document too
irb(main):005:0" HEREDOC
输出结果
"this is document\nthis is document too\n"
4 变换文字编码
NKF.nkf("-w -m0","转码的东西")
-w是转化成utf-8
Iconv.conv("变换后的码类型","变换前的码类型","字符串")
5 推测文字编码
NKF.guess("字符串")
6 复制字符串
str = "this is a string"
str.dup
str.clone
dup方法仅仅是复制了字符串的内容
clone方法复制了内容,同时也继承了特殊方法,污染(taint),冻结(freeze)等信息
7 处理字符串的单个文字
"需要处理的字符串".split("//")
8 处理字符串的单一字节
"abcdef".unpack("C*")
=> [97, 98, 99, 100, 101, 102]
另一种处理思路
irb(main):002:0> "abcdef".each_byte{|byte|p byte}
97
98
99
100
101
102
=> "abcdef"
9 将数组中的全部元素置换成一个对象
array = ["a","b","c"]
=> ["a", "b", "c"]
array.fill("d")
=> ["d", "d", "d"]
10 随机取得数组元素
array = [1,2,3,4,6]
=> [1, 2, 3, 4, 6]
array[rand(array.length)]
=> 3
12 将hash元素以插入顺序取出
使用PseudoHash
[url] http://raa.ruby-lang.org/project/pseudohash[/url]
13 使用巨大的离散型数组
如果使用array数组类型的话势必会造成大量的内存空间的占用
例如:
arr = Array.new
arr[1] = 1
arr[100] = 2
arr[3000] = 3
arr[100000] = 4
arr[10000000] = 5
这种情况下就应该使用hash来代替数组
14 虚拟变量_FILE_和_LINE_
_FILE_中存储有存放脚本本身文件的目录信息,使用File.expand_path(_FILE_)
_LINE_保存的是该行的行号
15 文件的读写
文件读
File.open("text.txt"){|file| ... }
文件写
新建文件
File.open("text.txt","w"){|file| ... }
在文件末尾添加内容
File.open("text.txt","a"){|file| ... }
二进制模式写入文件
File.open("text.txt","w"){|file|
file.binmode
file.write("hello,world")
}
16 读取正在写入的文件(如同linux下的 tail -f命令 )
我们可以通过file.read来读取文件的每一行一直到文件的末尾
因为使用IO类别的stdio函数限制的关系,有的平台上一旦读取文件中的数据到文件末尾的话,就不能再往下读取
在这里,使用一点技巧,便是在进行读取的同时,以File#seek(IO#seek)方法移动到相同的位置,从而避开这个限制
STDERR.sync = true
File.open("text.txt"){|file|
file.seek(0,IO::SEEK_END) #移动到文件尾端
while(true)
file.seek(0,IO::SEEK_CUR) #期待副作用并seek
if data = file.read
print data
end
sleep(0.5)
end
}
17 看见这个指数运算符,竟然惊了一下,用的太少了,我勒个去
3 ** 4 = 81
18 最大公因数,最小公倍数
require "rational"
# 最大公因数
1105.gcd(3570) #=>85
# 最小公倍数
123.lcm(33) #=>1353
19 浮点数的四舍五入等操作
四舍五入 round
无条件舍去 truncate
无条件进位 ceil(正数)floor(负数)