def valid_sheet_names
Company.find(@company_id).asset_types.pluck(:name).reject(&:nil?).map(&:downcase)
end
["hardware", "computer", "network", "mobile devices"]
這個函式回傳一個陣列。我想從字串中洗掉空格、點和下劃線。但我不知道我該怎么做
uj5u.com熱心網友回復:
我會過濾nil資料庫查詢中的值并避免首先將它們加載到記憶體中。然后我會通過一個tr電話來清理名稱:
def valid_sheet_names
Company.find(@company_id).asset_types.where.not(name: nil).pluck(:name)
names.map { |name| name.downcase.tr(' ._', '') }
end
uj5u.com熱心網友回復:
以@Sumak 的@spickermann 的回答為基礎
["hardware", "computer", "network", "mobile devices"].map do |asset_type|
asset_type.gsub(/[._\s]/, '')
end
哪個會像這樣進入你的代碼
def valid_sheet_names
Company.find(@company_id).asset_types.pluck(:name).reject(&:nil?).map { |name| name.downcase.gsub(/[._\s]/, '') }
end
gsub這里最好利用\s抓取任何型別空白的元字符。
uj5u.com熱心網友回復:
與您map在集合上的方式相同,您可以使用塊對其進行迭代:
["hardware", "computer", "network", "mobile devices"].map do |asset_type|
asset_type.delete(' ')
.delete('_')
.delete('.')
end
您的函式可能類似于:
def valid_sheet_names
asset_types = Company.find(@company_id).asset_types.pluck(:name).reject(&:nil?)
# I'd personally extract normalization to a specific function or module
asset_types.map do |asset_type|
asset_type.downcase
.delete(' ')
.delete('.')
.delete('_')
end
end
您也可以使用gsub(支持正則運算式)。雖然我發現delete當我們想要...洗掉時更明確
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/427183.html
標籤:轨道上的红宝石 红宝石 ruby-on-rails-3
上一篇:NoMethodErrorinTutorsController#createundefinedmethod`supert='for#<Tutor:0x00007fa5593f99f8&
下一篇:決議包含json字串的json
