我正在嘗試清理我的代碼并找出傳遞陣列方法的方法.all?。這是代碼:
if <condition>
parent_1.children.all? {|c| <condition>} ? result_of_true : result_of_false
else
parent_2.children.all? {|c| <condition>} ? result_of_true : result_of_false
end
他們都在使用.all? {|c| <condition>}. 我正在嘗試獲取它,以便我可以縮短此佇列,盡管也許我可以做一些事情,例如為每個孩子創建一個范圍并使用它,也許創建一個proc并使用它?
我嘗試了以下方法:
def new_all?
proc { |*args| args.all? {|c| c.attribute} }
end
if <condition>
parent_1.child.new_all? ? result_of_true : result_of_false
else
parent_2.child.new_all? ? result_of_true : result_of_false
end
# return example: [false, false, true]
或者可能是兒童班上的一些東西,比如:
def self.new_all?
all? {|c| <condition>}
end
必須有辦法做到這一點。我希望除了必須與實際Array班級一起作業之外還有其他事情。
這似乎回傳了一個結果陣列,但顯然不是您期望的單個布林值all?。
uj5u.com熱心網友回復:
為什么不定義一個簡單的方法,然后使用一行三元?
def new_all? (x)
x.all? {|item| <condition>} ? <result of true> : <result of false>
end
<other_condition> ? new_all?(a) : new_all?(b)
uj5u.com熱心網友回復:
簡化(哈!)代碼的一種簡單方法是從條件運算式的分支中提取重復代碼并將其移到條件運算式之外:
if <condition>
parent_1
else
parent_2
end.child.all? {|c| <condition>} ? result_of_true : result_of_false
順便說一句,我發現條件運算式和條件運算子的混合很難閱讀。事實上,我發現條件運算子一般難以閱讀。這在 Ruby 中也是完全沒有必要的。在 C 中需要條件運算子,因為它是一個運算子,因此是一個運算式,而條件陳述句則是一個陳述句。但是在 Ruby 中,條件運算式已經是一個運算式,因此不需要條件運算子。
所以,我可能會更像這樣寫:
if if condition
parent_1
else
parent_2
end.child.all? { |c| condition }
result_of_true
else
result_of_false
end
或許
if if condition then parent_1 else parent_2 end.child.all? { |c| condition }
result_of_true
else
result_of_false
end
但是,這要求將某些內容提取到方法或至少是變數中。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/400110.html
