赵龙 全栈之路

Rails Guides 零散笔记

| Comments

两种分支判断式:if & when

上下两段分支判断式代码等价,实现效果相同。

 1 a = 2 
 2 case a 
 3   when 1 then puts "a is 1" 
 4   when 2 then puts "a is 2" 
 5   when 3,4,5 then puts "a is in [3,4,5]" 
 6   else puts "a is not in [1,2,3,4,5]" 
 7 end 
 8  
 9 ##### 
10 a = 2 
11 if a == 1 
12   puts "a is 1" 
13 elsif a == 2 
14   puts "a is 2" 
15 elsif a == 3 
16   puts "a is in [3,4,5]" 
17 elsif a == 4 
18   puts "a is in [3,4,5]" 
19 elsif a == 5 
20   puts "a is in [3,4,5]" 
21 else 
22   puts "a is not in [1,2,3,4,5]" 
23 end

三元表达式

“三元表达式” 与 “普通实现方式” 实现效果相同,代码更简洁。

a = 2

# 三元表达式
puts a == 1 ? 'one' : 'not one'
> #=>  not one
 
# 普通实现方式 
if a == 1
  puts 'one'
else
  puts 'not one'
end
> #=>  not one

Comments

comments powered by Disqus