ruby学习笔记(8)--条件控制

#和其它OO语言有点不一样的是0会返回false
[1,0,true,nil,false,''].each{|e| print '{',e,'}' if e}#{1}{0}{true}{}
#difined? and or not
#difined?是一个新引入概念
puts 'defined?' if defined? a #expression  a未定义
puts defined? Fixnum #constant
#and &&
puts 'and' if 1 && nil and true #nil is false
#or ||
puts  'or' if 0||false||nil #0 is true
#not !
puts 'not' if !false &&( not nil) #not
#if unless
variable=0
if false
  variable=1
#elsif 其实更习惯else if
elsif  false
  variable=2
#也可以使用then
elsif false then variable=3
#也可以使用:代替then
elsif false : variable=4
elsif false :
  variable=5
else variable=6
end
#unless 可以认为是 if not
puts variable unless variable>6
#puts variable if not variable>6
#case when else end
year=700
puts case
  when year%400==0 : true
  when year%100==0 : false
  else year%4==0
  end
puts case year when 1..1000 : '1..1000'
  else 'other'
  end
#while until
variable=1
while variable<10
 variable+=2
end
puts variable #11
until variable<10
 variable-=2
end
puts variable #9
puts variable+=2 while variable<10 #11
#等同于以下结构
begin
puts variable-=2
end until variable<10 #9
#for
for i in 1..3
puts i
end
#ruby中更多的是使用
(1..3).each{|i| puts i}
#break next redo
index=0
index2=0
count=0
while true
 index+=1
 #中断继续下一轮循环
 next if index<3
 count+=1
 #重复本轮循环
 redo if count<3 
 index2+=1
 print 'index:',index,' index2:',index2,' count:',count,"\n"
 #index:5 index2:1 count:3
 #中断
 break if count>=3
end

3.times{
index-=1;
print index
#retry 重新开始一循环,比redo变态的是真正从新开始
#所以结果是43210,index=2然后3.times才能进行下去
retry unless index<3
}

本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/blackant2/archive/2006/12/04/1428800.aspx

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值