refactoring - Is there more idiomatic ruby to perform this iteration? -
i iterating through set of ids , want return first object returns true
when predicate method called on it. few lines of code worth thousand words:
def applicable_question(question_ids) ordered_ids(question_ids, order).detect |question_id| question = question.find_by(id: question_id) return question if question.applicable_for?(self) end end
stripping away domain terms:
def desired_thing(ids) ids.detect |id| thing = thing.new(id) return thing if thing.true? end end
is there more idiomatic approach here? specifically, feel abusing detect
. reached each
, break
, didn't far approach.
a requirement code not need instantiate large array of objects (activerecord subtypes example) find desired thing.
you have:
desired_thing = ids.detect |id| thing = thing.new(id) return thing if thing.true? end
if thing
found thing.true?
true
, detect
never returns element of ids
(to assigned desired_thing
) because it's preempted return
. on other hand, if block completes without return
being invoked, detect
returns nil
, assigns value desired_thing
, nil
value of no use in code follows. therefore better write:
ids.each |id| thing = thing.new(id) return thing if thing.true? end
Comments
Post a Comment