Geo 有一个不错的解决方案,但也有一些错失的机会。
如果您只查找一个元素,则使用 Enumerable#find 而不是 Enumerable#select 然后使用 Array#first 可能更有效。或者,您可以在选择期间简单地进行重新分配。
如果您查看建议的方法,如果找不到具有该名称的字段,您可能会触发异常:
# Original approach
my_fields = form.fields.select {|f| f.name == "whatever"}
# Chance of exception here, calling nil#whatever=
my_fields[1].whatever = "value"
我提倡使用 Enumerable#select 并简单地在循环内完成工作,这样更安全:
my_fields = form.fields.select do |f|
if (f.name == "whatever")
# Will only ever trigger if an element is found,
# also works if more than one field has same name.
f.whatever = 'value'
end
end
另一种方法是使用最多返回一个元素的 Enumerable#find:
# Finds only a single element
whatever_field = form.fields.find { |f| f.name == "whatever" }
whatever_field and whatever_field.whatever = 'value'
当然,您总是可以在代码中添加异常捕获,但这似乎适得其反。