# 控制語句
每個編程語言都必須有控制語句,Ruby也不例外。Ruby中的控制語句包含下面幾種:
- 條件選擇語句 (if/ case)
- 循環語句 (while/ for/ until)
- 迭代語句 (each)
### 條件選擇語句 (if/ case)
~~~
x=1
if x > 2
puts "x is greater than 2"
elsif x <= 2 and x!=0
puts "x is 1"
else
puts "I can't guess the number"
end
~~~
通過上面例子,基本可以了解if語句的用法了。和其他語言沒什么兩樣。不過在Ruby中,如果你的條件只有一重,可以使用下面的格式,也叫if修飾符:
~~~
word = 'world'
puts "hello #{word}" if word
#=> "hello world"
~~~
上面的兩段代碼中,if后面只要跟表示true的表達式,就可以執行if分支,否則就執行其他if分支,比如elsif,或else分支。。
### 循環語句 (while/ for/ until)
直接看例子吧:
~~~
@i = 0;
num = 5;
while @i < num do
puts("Inside the loop i = #@i" );
@i +=1;
end
~~~
while循環語句,上面的代碼中有一段:
~~~
puts("Inside the loop i = #@i" );
~~~
這句中的#@i 實際上是#{@i},在變量為非本地變量情況下,Ruby允許你省略{}。
~~~
$i = 0;
$num = 5;
begin
puts("Inside the loop i = #$i" );
$i +=1;
end while $i < $num
~~~
可以使用begin...end while語句,類似于其他語言的do...while。
until語句:
~~~
$i = 0;
$num = 5;
until $i > $num do
puts("Inside the loop i = #$i" );
$i +=1;
end
~~~
跟while的條件相反才執行。
for語句:
~~~
for i in 0..5
puts "Value of local variable is #{i}"
end
~~~
### 迭代語句 (each)
each是我們最常用的迭代語句,一般都用它來替代循環語句。
~~~
[1, 2, 3].each do |i|
puts i
end
~~~
這里涉及到do...end代碼塊,我們下節會講到這個概念。
- 序
- Chapter 1: 初識Chef
- 一些背景
- Chef vs Puppet
- Chapter 2: Chef應用
- Chef架構
- Chef能做什么
- Chef組件
- Chef環境安裝
- chef-server
- opscode-chef
- chef-solo
- Chef實戰
- 實戰前的必修理論
- 使用Chef
- Chapter 3: Ruby基礎
- 對象與方法
- 標識符
- 類與模塊
- 數據類型
- 真與假
- 控制語句
- 代碼塊
- Chapter 4: Chef源碼架構
- Rubygems與gem
- bundler
- Chef源碼組織
- Chapter 5: Rails基礎
- Rails是什么
- MVC架構
- Restful
- Rails組成與項目結構
- Chapter 6: Chef Server WebUI
- Chef Server Webui組織結構
- Chef Rest API
- 參考