如果在数组中找到对象,我目前正在使用此代码直接从函数中返回对象:
already_existing = my_array.find { |v| ... predicate ... }
return already_existing if already_existing
# ...
# Remaining of the function should be executed if object not found
是否有一种优雅的方法可以将其转换为单线?
注意:当然无需两次调用find
,也不必先调用include?
,然后再调用find
,因为这样会降低性能)
答案 0 :(得分:4)
您可能会短路。
my_array.find { |v| ... predicate ... } or begin
# the other logic
end
但是我个人会选择return existing if existing
。在这种情况下,治愈胜于疾病。
答案 1 :(得分:0)
是否有一种优雅的方法可以将其转换为单线?
当然可以!实际上,由于换行符在Ruby中是可选的,所以任何任意复杂的Ruby程序都可以变成单行代码:
already_existing = my_array.find { |v| ... predicate ... }; return already_existing if already_existing
答案 2 :(得分:-2)
Facets库具有#find_yield
方法。它可以帮助将代码统一组织。也可以使用“ map.detect”组合来完成。
基本上,您需要做return something that found OR call other stuff
:
require "facets"
test_arrays = [[1, 2], [1, 2, 3]]
# with facets library
test_arrays.each do |my_array|
puts my_array.find_yield{ |i| j = i + 1; j if j % 4 == 0 } || "other_logic_result"
end
# => other_logic_result
# => 4
# with pure ruby methods
test_arrays.each do |my_array|
puts my_array.lazy.map { |i| i + 1 }.detect { |j| j % 4 == 0 } || "other_logic_result"
end
# => other_logic_result
# => 4