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..end
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..end
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
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
您可以使用三元運算符的時候,子句中:
case search_term
when 'a'
ptr = 0
when 'b'
ptr = 1
when 'c'
ptr = location == 'xyz' ? 0 : 2
else
ptr = 99
end
兩個備註:
==
比較(=
是一個賦值)這將是另一種可能性:
ptr = (location == 'xyz') ? 0 : 2
括號不是必需的,但我發現它更具可讀性。
如果我寫它簡潔地我會用:是不是真的建議
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
的恢復默認值的功能:
測試他們:
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
定義散列上飛是OK,如果你在不長的循環或迭代很多值的search_term
或有沒有很多鍵/值對被合併。通常我會用第一種風格來定義它。
這不會產生與OP邏輯相同的結果。如果'location =='xyz''這會導致'ptr'沒有被設置爲任何東西。 – moveson
@moveson你是對的,只是錯過了完整的邏輯。我修改了代碼。 – knut