-
ruby 语法(转)
添加时间:2013-5-14 点击量:转自 http://www.2cto.com/kf/201210/159906.html
1. if语句
if语句是示例如下:
[ruby]
#encoding:gbk
FAN = 10;
if FAN>5
puts FAN > 5;
elsif FAN>3
puts 3 < FAN < 5;
else
puts FAN < 3;
end#encoding:gbk
FAN = 10;
if FAN>5
puts FAN > 5;
elsif FAN>3
puts 3 < FAN < 5;
else
puts FAN < 3;
end2. unless语句
unless语句和if相反,若是前提不成立则履行
[ruby]
#encoding:gbk
FAN = 10;
if FAN>5
puts FAN > 5;
elsif FAN>3
puts 3 < FAN < 5;
else
puts FAN < 3;
end
puts ;
puts unless test unless FAN > 20;#encoding:gbk
FAN = 10;
if FAN>5
puts FAN > 5;
elsif FAN>3
puts 3 < FAN < 5;
else
puts FAN < 3;
endputs ;
puts unless test unless FAN > 20;
3. case语句
[ruby]
#encoding:gbk
FAN = 10;
if FAN>5
puts FAN > 5;
elsif FAN>3
puts 3 < FAN < 5;
else
puts FAN < 3;
end
puts ;
puts unless test unless FAN > 20;
puts ;
NUM = 6;
case NUM
when 5
puts 5;
when 6
puts 6;
end#encoding:gbk
FAN = 10;
if FAN>5
puts FAN > 5;
elsif FAN>3
puts 3 < FAN < 5;
else
puts FAN < 3;
endputs ;
puts unless test unless FAN > 20;
puts ;
NUM = 6;
case NUM
when 5
puts 5;
when 6
puts 6;
end
case语句中的when 还可所以一个局限。
4. while轮回
[ruby]
#encoding:gbk
FAN = 10;
a = 1;
while a < FAN do
puts a;
a=a+1;
end#encoding:gbk
FAN = 10;
a = 1;while a < FAN do
puts a;
a=a+1;
end
Ruby中不支撑++运算符
5. for轮回
[ruby]
#encoding:gbk
FAN = 10;
a = 1;
while a < FAN do
puts a;
a=a+1;
end
FOODS = [巧克力,面包,蛋糕,牛奶];
for f in FOODS do
puts f;
end#encoding:gbk
FAN = 10;
a = 1;while a < FAN do
puts a;
a=a+1;
endFOODS = [巧克力,面包,蛋糕,牛奶];
for f in FOODS do
puts f;
end
还可以遍历Hash对象
[ruby]
#encoding:gbk
FAN = 10;
a = 1;
while a < FAN do
puts a;
a=a+1;
end
FOODS = [巧克力,面包,蛋糕,牛奶];
for f in FOODS do
puts f;
end
Stus = {小王=>29,小李=>23,小宋=>25};
for name,age in Stus do
puts name, age;
end#encoding:gbk
FAN = 10;
a = 1;while a < FAN do
puts a;
a=a+1;
endFOODS = [巧克力,面包,蛋糕,牛奶];
for f in FOODS do
puts f;
endStus = {小王=>29,小李=>23,小宋=>25};
for name,age in Stus do
puts name, age;
end6. 迭代器
应用数组或者Hash对象自带的迭代器
[ruby]
#encoding:gbk
FAN = 10;
a = 1;
FOODS = [巧克力,面包,蛋糕,牛奶];
FOODS.each do |f|
puts f;
end
Stus = {小王=>29,小李=>23,小宋=>25};
Stus.each do |name,age|
puts name,age;
end#encoding:gbk
FAN = 10;
a = 1;
FOODS = [巧克力,面包,蛋糕,牛奶];
FOODS.each do |f|
puts f;
endStus = {小王=>29,小李=>23,小宋=>25};
Stus.each do |name,age|
puts name,age;
end7. 轮回把握
[ruby]
loop{
puts (((((((((((((((()))))))))))))))))))):
i=i+1;
if(i>3)
break;
end
}loop{
puts (((((((((((((((()))))))))))))))))))):
i=i+1;
if(i>3)
break;
end
}
应用loop创建一个根蒂根基的轮回。
容易发怒的意思就是: 别人做了蠢事, 然后我们代替他们, 表现出笨蛋的样子。—— 蔡康永
其他的轮回把握:
next : 终止当前的轮回,进入下一个轮回,相当与其他编程说话的continue;
redo : 跳出本次轮回,进入下一次轮回,应用redo语句跳入下一次轮回的时辰,不搜检前提是否成立,直接进入轮回。
return : 停止轮回