【问题标题】:How can remove some special character from string of array如何从数组字符串中删除一些特殊字符
【发布时间】:2021-12-09 00:25:55
【问题描述】:
def valid_sheet_names
Company.find(@company_id).asset_types.pluck(:name).reject(&:nil?).map(&:downcase)
end
["hardware", "computer", "network", "mobile devices"]
这个函数返回一个数组。我想从字符串中删除空格、点和下划线。但我不知道我该怎么做
【问题讨论】:
标签:
ruby-on-rails
ruby
ruby-on-rails-3
【解决方案1】:
以@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,它可以抓取任何类型的空格。
【解决方案2】:
我会在数据库查询中过滤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
【解决方案3】:
与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 在我们想要删除时更加明确