一. 条件判断
详情参看:https://www.runoob.com/ruby/ruby-decision.html
1.详情实例(看看就中了)
#---------------# # LOL场均人头 #---------------# point_game = 15 if point_game >= 30 puts "大大神" elsif point_game >= 20 puts "大神" else puts "还中吧" end #---------------# # 我要玩游戏 #---------------# #《绝地求生》(PUBG) PUBG_SteamPrice = 98 #unless=只要不 unless PUBG_SteamPrice < 100 #大于等于100的时候 puts "玩蛋去" else #小于100的时候 puts "真香!" end #---------------# # 今天是星期几? #---------------# week_day = 0 case week_day when 0,7 puts "星期日" when 1 puts "星期一" when 2 puts "星期二" when 3 puts "星期三" when 4 puts "星期四" when 5 puts "星期五" when 6 puts "星期六" else raise Exception.new("没这天") end
注:Python中没有unless和case when这种条件判断的写法
2. 值得注意的
(1). Ruby if 修饰符
(2).Ruby中的case when
二. 循环
详情参看:https://www.runoob.com/ruby/ruby-loop.html
1.详情实例
#循环数组 game_list = ["塞尔达传说", "超级马里奥", "开心剪纸"] for game in game_list do puts game end #循环1-5 for num in 1..5 do puts num end #循环1-4 for num in 1...5 do puts num end #while循环 index = 0 while index < 5 do puts "while.index=" + index.to_s index+=1 end #untile index = 0 until index == 5 do puts "until.index=" + index.to_s index+=1 end
2.值得注意的
(1).Ruby while 修饰符
(2).Ruby until 语句(基本用不着)
(3).Ruby next 语句
(4).Ruby redo 语句
(5).特殊循环
#each循环 gamelist = ["塞尔达传说", "超级马里奥", "开心剪纸"] gamelist.each { |game| puts game } gamelist.each do |game| puts game end gamelist.each_with_index do |game,i| puts i.to_s + "." + game end #times循环 5.times do |i| puts "第 #{i+1} 次times循环" end #step循环(根据步长的循环) 1.step(10,3) do |i| puts "#{i}" end
#upto(从哪到哪) 2.upto(5) do |i| puts "updo=" + i.to_s end #downto 5.downto(2) do |i| puts "downto=" + i.to_s end
三. Ruby的异常处理
begin #有可能发生错误的处理 puts ">处理开始" #raise "my raise error!" #10 / 0 rescue => e #错误发生时 puts "X错误发生!" puts e else #正常处理时 puts "O正常处理" ensure #最后处理,无论是否发生处理(final) puts "_最后的扫尾处理" end