Ruby3 流程控制

if/else/elsif

1
2
3
4
5
6
7
8
9
a = "hello"
b = false
if a
    p a
elsif b
    p b
else
    p "ok"
end

unless

unless相当于if的反向断言

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
    unless false
        "ok"
    end
    # => "ok"

## if/unless

    a = 1 if a != 1 #如果a不是1 则a复制为1
    b = 2 unless defined?(b) #如果b未定义 那么就定义b赋值为2

## case

    case a
    when 1
        1
    when /hello/
        "hello world"
    when Array
        []
    else
        "ok"
    end

## while

    a = 0
    while a < 100 do
        p a
        a += 1
    end

ruby 没有++和–操作符

Iterators

1
2
3
4
5
6
7
    for x in [1, 2, 3] do
        p x
    end
    [1, 2, 2].each do |x|
        p x
    end
    10.times {|x| p x}
updatedupdated2024-12-092024-12-09