判断

1
2
3
4
5
6
7
8
9
10
11
12
>> x = 4
=> 4
>> x < 5
=> true
>> x <= 4
=> true
>> x > 4
=> false
>> false.class
=> FalseClass
>> True.class
=> TrueClass

也就是说, Ruby中有取值为true或false的表达式。和其他语言一样, Ruby中的true和false也是一等对象(first-class object)。它们可用来执行下列涉及条件判断的代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
>> x = 4
=> 4
>> puts 'This appears to be false.' unless x == 4
=> nil
>> puts 'This appears to be true.' if x == 4
This appears to be true.
=> nil
>> if x == 4
>* puts 'This appears to be true.'
>* end
This appears to be true.
=> nil
>> unless x == 4
>* puts 'This appears to be false.'
>* else
>* puts 'This appears to be true.'
>* end
This appears to be true.
=> nil
>> puts 'This appears to be true.' if not true
=> nil
>> puts 'This appears to be true.' if !true
=> nil

当你使用if或unless时,既可选用块形式(if condition, statements , end),也可选用单行形式(statements if condition)。

循环

while 和 until 亦是如此:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
>> x = 1
=> 1
>> x = x + 1 while x < 10
=> nil
>> x = x - 1 until x == 1
=> nil
>> x
=> 1
>> while x < 10
>* x = x + 1
>* puts x
>* end
2
3
4
5
6
7
8
9
10
=> nil

注意, =用于赋值,而==用于判断是否相等。在Ruby中,每种对象都有自己特有的相等概念。数字对象的值相等时,它们相等。

Comments