ruby 有通常的控制结构:if语句和while循环,它们没有{},使用end作为结束:
1.if
if count > 10
puts "Try again"
elsif tries == 3 #使用 elsif 而不是else if
puts "You lose"
else
puts "Enter a number"
end
2.while
while weight < 100 and num_pallets <= 30 #使用 and 表示"与"
pallet = next_pallet()
weight += pallet.weight
num_pallets += 1
end
while line = gets #使用while读取文件,gets方法在读取文件时,遇见文件尾返回nil,正如前面所说的,nil表示false
puts line.downcase
end
3.statement modifier:一种编程的捷径
if radiation > 3000
puts "Danger, Will Robinson"
end
使用 statement modifer 重写以后:puts "Danger, Will Robinson" if radiation > 3000
它也表示了同样的效果,while也可以
square = 2
while square < 1000
square = square*square
end
使用 statement modifer 重写以后:
square = 2
square = square*square while square < 1000
循环被简化成为一行
联系客服