Ruby编程:操作符与控制结构详解
一、触发器函数
触发器函数在编程中用于根据特定条件改变状态。在Ruby中,我们可以定义如下两个触发器函数。
$state = false # Global storage for flip-flop state
def flipflop(x) # Test value of x against flip-flop
if !$state # If saved state is false
result = (x == 3) # Result is value of lefthand operand
if result # If that result is true
$state = !(x == 5) # Then saved state is not of the righthand operand
end
result # Return result
else # Otherwise, if saved state is true
$state = !(x == 5) # Then save the inverse of the righthand operand
true # And return true without testing lefthand
end
end
(1..10).each {|x| print x
超级会员免费看
订阅专栏 解锁全文
8

被折叠的 条评论
为什么被折叠?



