Geoにはまともな解決策がありますが、そこにはいくつかの機会を逃しています。
要素を1つだけ検索する場合は、Enumerable#selectの代わりにEnumerable#findを使用してから、その上に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
もう1つのアプローチは、最大で1つの要素を返すEnumerable#findを使用することです。
# Finds only a single element
whatever_field = form.fields.find { |f| f.name == "whatever" }
whatever_field and whatever_field.whatever = 'value'
もちろん、例外キャッチを使用してコードをいつでもペッパーすることができますが、それは逆効果のようです。