Ruby on Rails 学习笔记之四 – 逻辑语句
一、判断语句
1. if 语句: 当条件成立时执行
l if 条件 .. elsif 条件 .. else … end
l elseif 可以有多个
l puts "No cars have been produced yet." if Car.count.zero? 作为语句修饰符
2. unless 语句 : 当条件不成立时执行
l unless 条件 … else … end
l 只能有一个else , 没有 elsif
l puts "Service due!" unless kitt.mileage < 25000 作为语句修饰符
二、循环语句(loop)
1. while 当条件成立时循环
l while 条件 … end
2. until 当条件不成立时循环,成立时退出
l until 条件 … end
3. for 遍历,相当于其他语言的foreach
l for car in [ kitt, herbie, batmobile, larry ] puts car.mileage end
三、语句块(block)
1. Array.each do | 变量 | … end
l [ kitt, herbie, batmobile, larry ].each do |car_name| puts car_name.mileage end
2. Hash.each do |key,value| … end
l car_colors = { 'kitt' => 'black', 'herbie' => 'white', 'batmobile' => 'black', 'larry' => 'green' } car_colors.each do |car_name, color| puts "#{car_name} is #{color}" end
3. times : (Integer 对象的方法)
l 10.times { Car.new } puts "#{Car.count} cars have been produced."
4. upto : (Integer 对象的方法)
l 5.upto(7) { |i| puts i } 输出 5 6 7三行