0

我怎样才能避免打字

TypeOfVoyagePortActivity.find_by_description(activity_description)

两次?

这是我在其中使用它的上下文:

 if TypeOfVoyagePortActivity.find_by_description(activity_description)
   pl.activity = TypeOfVoyagePortActivity.find_by_description(activity_description)
 else
   pl.activity = TypeOfVoyagePortActivity.find_by_description("Custom") 
 end
4

2 回答 2

5
model = TypeOfVoyagePortActivity
pl.activity = model.find_by_description(activity_description) ||
  model.find_by_description("Custom")
于 2012-12-04T20:28:01.713 回答
1

您可以将结果分配给find_by_description变量

 if t = TypeOfVoyagePortActivity.find_by_description(activity_description)
   pl.activity = t
 else
   pl.activity = TypeOfVoyagePortActivity.find_by_description("Custom") 
 end

或者作为更好的选择:

p1.activity = [activity_description, "Custom"].each_with_object(nil) do |a, memo|
  memo ||= TypeOfVoyagePortActivity.find_by_description(a)
end
于 2012-12-04T20:27:34.833 回答