我有以下方法:
def fetch_something
@fetch_something ||= array_of_names.inject({}) do |results, name|
begin
results[name] = fetch_value!(name)
rescue NoMethodError, RuntimeError
next
end
results
end
end
其目的:它获取可能引发错误的给定值name
,在这种情况下,它将忽略name
并尝试下一个。
虽然这工作正常,但我从 Rubocop 收到一个错误,上面写着:
Lint/NextWithoutAccumulator:在 reduce 中将 next 与累加器参数一起使用。
谷歌搜索该错误导致我到http://www.rubydoc.info/gems/rubocop/0.36.0/RuboCop/Cop/Lint/NextWithoutAccumulator,它说不要省略累加器,这将导致方法看起来像这样:
def fetch_something
@fetch_something ||= array_of_names.inject({}) do |results, name|
begin
results[name] = fetch_value!(name)
rescue NoMethodError, RuntimeError
next(name)
end
results
end
end
问题是,这种变化打破了原本的工作方法。关于如何解决这个问题的任何想法?
更新:示范示例:array_of_names = ['name1','name2','name3']
def fetch_value!(name)
# some code that raises an error if the name doesn't correspond to anything
end
fetch_something
# => {'name1' => {key1: 'value1', ...}, 'name3' => {key3: 'value3', ...}}
# 'name2' is missing since it wasn't found durcing the lookup