我正在遍历一组 id,并希望返回第一个在调用谓词方法时返回 true
的对象。几行代码抵一千字:
def applicable_question(question_ids)
ordered_ids(question_ids, order).detect do |question_id|
question = Question.find_by(id: question_id)
return question if question.applicable_for?(self)
end
end
剥离域术语:
def desired_thing(ids)
ids.detect do |id|
thing = Thing.new(id)
return thing if thing.true?
end
end
这里有更惯用的方法吗?具体来说,我觉得我在滥用 detect
。我立即使用了 each
和 break
,但这种方法并没有取得太大进展。
此代码的一个要求是它不需要实例化大量对象(例如 ActiveRecord 子类型)来找到所需的东西。
最佳答案
你有:
desired_thing = ids.detect do |id|
thing = Thing.new(id)
return thing if thing.true?
end
如果 thing
被发现 thing.true?
为 true
,detect
永远不会返回元素ids
(将分配给 desired_thing
),因为它被 return
抢占了。另一方面,如果 block 在没有调用 return
的情况下完成,则 detect
返回 nil
并将该值分配给 desired_thing
,但是 nil
值在后面的代码中没有用。因此最好只写:
ids.each do |id|
thing = Thing.new(id)
return thing if thing.true?
end
关于ruby - 是否有更多惯用的 ruby 来执行此迭代?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29176490/