不少人都对rails感兴趣,我也是,不过我不急着用,所以不直接去学习rails,而想先稳当一点先把Ruby大致过一遍,熟悉下Ruby的特性。
变量命名规则:
======================================================
局部变量--以小写字母或下划线_开头,如:alpha, _ident, some_var
全局变量--以$开头,如:$beta, $B12vitamin, $NOT_CONST
实例变量--以@开头,如:@foobar, @thx1138, @NOT_CONST
类变量-----以@@开头,如:@@phydeaux, @@my_var, @@NOT_CONST
常量--------以大写字母开头,如:K6chip, Length, LENGTH
注释
===============================================================
以#开头,如:
a = 1 + 2 #注释部分...
#又是注释部分...
print "# 这里不是注释部分"
嵌入式文档(可用RDTOOL生成文档)
=======================================================
以=begin开头,以=end结尾,如:
=begin
this part is the embbed document.
hello,ruby!
=end
字符串
======================================================
可以用双引号和单引号,如:
"hello,world!"
'hello,every one!'
两者不同点:
1.双引号可以解释所有支持的转义字符,如:
"hello,/t world!/n"
单引号则只能支持两种://和/'
'hello,// world!'
2.双引号中可以嵌入变量或表达式并计算,如:
myname = "zarknight""hello,#{ myname}!" #结果为hello,zarknight!
"The sum is #{ 1+2+3} ."
而单引号则会当作普通字符来处理。
一般情况下,嵌入的变量或表达式需要以#为前缀,包含在括号内,如:#{abc},但如果是以$或@开头的变量,可以省略括号,如#$abc
%q和%Q是广义的单引号和双引号,可以这样使用:
%q{ We can embed // and /} in this string.}
%Q("Hello, #{ name} ," I said to her.)
============================================================
``(反引号)或%x可以执行系统命令,如:
·grep i meta *.html | wc l·
%x[grep i meta *.html | wc l]
============================================================
ruby中的正则表达式示例如下:
/^[a-zA-Z]*$/
或
%r{^[a-zA-Z]}
============================================================
Ruby的数组:
数组可以包含任意类型的元素,包括混合类型的元素,用法如下:
[1, 2, 3]
[1, 2, "buckle my shoe"]
[1, 2, [3,4], 5]
["alpha", "beta", "gamma", "delta"]
可以用%w方便的生成字符串数组(前提是目标字符串中没有空格,否则,生成出来的就和你的意愿不一样了),如:
%w{aaa bbb ccc ddd}
============================================================
Ruby的hash,也称联合数组或字典,用法如下:
{ 1=>1, 2=>4, 3=>9, 4=>16, 5=>25, 6=>36 }
{ "cat"=>"cats", "ox"=>"oxen", "bacterium"=>"bacteria" }
{ "hydrogen"=>1, "helium"=>2, "carbon"=>12 }
{ "odds"=>[1,3,5,7], "evens"=>[2,4,6,8]}
{"foo"=>123, [4,5,6]=>"my array", "867-5309"=>"Jenny" }
============================================================
循环与分支
============================================================
if x < 5 then
statement1
end
等价形式:
unless x >= 5 then
statement1
end
也可以这样写:
statement1 if x < 5
还可以这样做赋值:
x = if x < 5 then a else b end
Ruby的case与语句示例:
case x
when "hello"
puts "oper one"
when "world"
puts "oper two"
else
puts "other oper"
end
循环的用法有很多种:
# while循环===========================================================
i=0
while i < list.size do
print "#{ list[i]} "
i += 1
end
# until循环
i=0
until i == list.size do
print "#{ list[i]} "
i += 1
end
# post-test while(即先执行一次循环体再做判断的while循环)
i=0
begin
print "#{ list[i]} "
i += 1
end while i < list.size
# post-test until(即先执行一次循环体再做判断的until循环)
i=0
begin
print "#{ list[i]} "
i += 1
end until i == list.size
# for循环
for x in list do
print "#{ x} "
end
# 'each' 迭代器
list.each do |x|
print "#{ x} "
end
# 'loop' 方法
i=0
n=list.size-1
loop do
print "#{ list[i]} "
i += 1
break if i > n
end
# 'times' 迭代器
n=list.size
n.times do |i|
print "#{ list[i]} "
end
# 'upto' 迭代器
n=list.size-1
0.upto(n) do |i|
print "#{ list[i]} "
end
# for循环2
n=list.size-1
for i in 0..n do
print "#{ list[i]} "
end
# 'each_index'迭代器
list.each_index do |x|
print "#{ list[x]} "
end
Ruby的block机制
示例一:
def repeate_test(condition)
yeild
retry if not condition
end
j=0
repeat_test (j < 10) do {
j+=1;
print j,"/n"
}
实例二:
def my_sequence
for i in 1..10 do
yield i
end
end
my_sequence { |x| print x**3, "/n"}
==========================================================
Ruby的异常处理机制:
使用raise抛异常(rails不是关键子,是Kernel模块的一个方法,它还有个别名fail),用法:
raise # Example 1使用ensure(相当与java中的finally)来善后:
raise "Some error message." # Example 2
raise ArgumentError # Example 3
raise ArgumentError, "Invalid data." # Example 4
raise ArgumentError.new("Invalid data.") # Example 5
使用rescue(相当与java中的catch)处理异常:
begin
x = Math.sqrt(y/z)
# ...
rescue ArgumentError
print "Error taking square root./n"
rescue ZeroDivisionError
print "Attempted division by zero./n"
或
begin
x = Math.sqrt(y/z)
# ...
rescue => err
print err, "/n"
end
end
raise ArgumentError, "Invalid data.", caller[0]
retry关键字可以用来重新执行begin开始的语句。
begin
# Error-prone code...
rescue
# Handle exceptions
ensure
# This code is always executed
end