在處理大量屬性的 API 中,經常出現以下模式
if !article[:ingredients].nil?
clean_ingredients = article[:ingredients].tr('*$ !@#?', ' ')
ingredients = clean_ingredients.downcase.capitalize
else
ingredients = nil
end
對于 JSON 字串:{ "id": "YYYYYY", "article": [ { "ingredients": "long string", [...]
不幸的是,方法定義為
def empty_and_clean(array_element, element_attribute)
if !array_element[:element_attribute].nil?
clean_ingredients = array_element[:element_attribute].tr('*$ !@#?', ' ')
ingredients = clean_ingredients.downcase.capitalize
else
ingredients = nil
end
end
不能在方法中呼叫,empty_and_clean(article, ingredients) 因為它回傳
undefined local variable or method 'ingredients'
什么語法允許重構這個模式?
uj5u.com熱心網友回復:
你可以這樣呼叫你的empty_and_clean方法:
empty_and_clean(article, :ingredients)
只需修改empty_and_clean為element_attribute直接使用,而不是使用符號:element_attribute。
我建議你閱讀更多關于 Ruby 中的符號來理解它是如何作業的。
此外,array_element是一個誤導性的名稱,因為它是一個陣列,而不是陣列的元素。array會稍微好一點,但仍然太通用了。也許objects或其他描述陣列中實際內容的東西。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/368668.html
標籤:红宝石轨道
