case search_term
when 'a'
ptr = 0
when 'b'
ptr = 1
when 'c'
ptr = 2
else
ptr = 99
end
if location = 'xyz' and search_term = 'c'
ptr = 0
end
有没有办法在case语句中包含if??
答案 0 :(得分:4)
ptr = case search_term
when 'a'
0
when 'b'
1
when 'c'
if location == 'xyz' then #note the ==
0
else
2
end
else
99
end
答案 1 :(得分:3)
case
构造通常不用于复杂逻辑。虽然您可以找到一个可行的解决方案(如@steenslag的答案),但这条路径会因条件变得更复杂而导致麻烦。具有三个或四个分支的case
语句是可行的,但已经有点代码味道。不仅如此,还会产生问题。将条件放在when
分支中会使问题复杂化。
您可以考虑使用小方法将事情分解为单独的职责。这将使您的代码在将来更容易理解,扩展和修改。
def pointer # Ruby convention is to use real words where practical
special_condition? ? 0 : pointer_base
end
def special_condition?
location == 'xyz' && search_term == 'c'
end
def pointer_base
search_term_map[search_term] || 99
end
def search_term_map
('a'..'c').zip(0..2).to_h # This could just as easily be ('a'..'z').zip(0..25).to_h
end
答案 2 :(得分:0)
您可以在when子句中使用三元运算符:
case search_term
when 'a'
ptr = 0
when 'b'
ptr = 1
when 'c'
ptr = location == 'xyz' ? 0 : 2
else
ptr = 99
end
两个评论:
==
进行比较(=
是作业)答案 3 :(得分:0)
这是另一种可能性:
ptr = (location == 'xyz') ? 0 : 2
不需要括号,但我发现它更具可读性。
答案 4 :(得分:0)
如果我简洁地写作,我会使用:
ptr = case search_term
when 'a'
0
when 'b'
1
when 'c'
location == 'xyz' ? 0 : 2
else
99
end
虽然许多语言允许使用三元语句,但并不是真的值得推荐,主要是因为太多人不了解如何使用它们,或者安全/可维护地使用它们。
或者可以这样写:
ptr = case search_term
when 'a'
0
when 'b'
1
when 'c'
if location == 'xyz'
0
else
2
end
else
99
end
如果您真的想玩得开心,可以利用Hash.new
的功能返回默认值:
Hash.new(99).merge(
'a' => 0,
'b' => 1,
'c' => location == 'xyz' ? 0 : 2
)[search_term]
测试它们:
search_term = 'a'
location = 'xyz'
ptr = case search_term
when 'a'
0
when 'b'
1
when 'c'
if location == 'xyz'
0
else
2
end
else
99
end
ptr # => 0
Hash.new(99).merge(
'a' => 0,
'b' => 1,
'c' => location == 'xyz' ? 0 : 2
)[search_term] # => 0
search_term = 'b'
location = 'xyz'
ptr = case search_term
when 'a'
0
when 'b'
1
when 'c'
if location == 'xyz'
0
else
2
end
else
99
end
ptr # => 1
Hash.new(99).merge(
'a' => 0,
'b' => 1,
'c' => location == 'xyz' ? 0 : 2
)[search_term] # => 1
search_term = 'c'
location = 'xyz'
ptr = case search_term
when 'a'
0
when 'b'
1
when 'c'
if location == 'xyz'
0
else
2
end
else
99
end
ptr # => 0
Hash.new(99).merge(
'a' => 0,
'b' => 1,
'c' => location == 'xyz' ? 0 : 2
)[search_term] # => 0
search_term = 'c'
location = 'abc'
ptr = case search_term
when 'a'
0
when 'b'
1
when 'c'
if location == 'xyz'
0
else
2
end
else
99
end
ptr # => 2
Hash.new(99).merge(
'a' => 0,
'b' => 1,
'c' => location == 'xyz' ? 0 : 2
)[search_term] # => 2
search_term = 'z'
location = 'xyz'
ptr = case search_term
when 'a'
0
when 'b'
1
when 'c'
if location == 'xyz'
0
else
2
end
else
99
end
ptr # => 99
Hash.new(99).merge(
'a' => 0,
'b' => 1,
'c' => location == 'xyz' ? 0 : 2
)[search_term] # => 99
如果您没有长时间循环或迭代search_term
的很多值,或者没有很多键/值对,那么动态定义哈希是可以的。合并。通常我会使用第一种风格来定义它。