`
liss
  • 浏览: 826356 次
  • 性别: Icon_minigender_1
  • 来自: 广州
社区版块
存档分类
最新评论

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

    博客分类:
  • Ruby
阅读更多

#和其它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

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics