Home > Net >  How can remove some special character from string of array
How can remove some special character from string of array

Time:10-22

def valid_sheet_names
   Company.find(@company_id).asset_types.pluck(:name).reject(&:nil?).map(&:downcase)
end

["hardware", "computer", "network", "mobile devices"]

this function return an array.i want to remove space, dot and underscore from string. but i don'y know how can i do this

CodePudding user response:

The same way you map over the collection, you can iterate it using a block:

["hardware", "computer", "network", "mobile devices"].map do |asset_type|
  asset_type.delete(' ')
            .delete('_')
            .delete('.')
end

Your function could look something like:

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

You can also use gsub (which supports regular expressions). Though I found delete more explicit when we want to... delete

  • Related