Ruby on Rails 入门之:(8) Ruby中条件语句
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";
end
2. 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";
end
puts "*******************************";
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";
end
puts "*******************************";
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;
end
FOODS = ["巧克力","面包","蛋糕","牛奶"];
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;
end
FOODS = ["巧克力","面包","蛋糕","牛奶"];
for f in FOODS do
puts f;
end
Stus = {"小王"=>"29","小李"=>"23","小宋"=>"25"};
for name,age in Stus do
puts name, age;
end
6. 迭代器
使用数组或者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;
end
Stus = {"小王"=>"29","小李"=>"23","小宋"=>"25"};
Stus.each do |name,age|
puts name,age;
end
7. 循环控制
[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 : 结束循环
补充:Web开发 , 其他 ,