简体   繁体   English

如何在 ruby 中使用带有数组元素的 gsub

[英]How to use gsub with array element in ruby

I am trying to remove some speicial character from array but it showing error我正在尝试从数组中删除一些特殊字符,但它显示错误

undefined method gsub! for array 


 def get_names
   Company.find(@company_id).asset_types.pluck(:name).reject(&:nil?).gsub!(/([^,-_]/, '').map(&:downcase)
 end

As it was said arrays don't respond to gsub!据说 arrays 不响应gsub! . . An array is a collection of items that you might process.数组是您可能处理的项目的集合。 To achieve what you want you should call gsub on each item.为了实现你想要的,你应该在每个项目上调用gsub Notice the difference between gsub!注意gsub! andgsub methods.gsub方法。 gsub! will modify a string itself and might return nil whereas gsub will just return a modified version of a string.将修改字符串本身并可能返回nilgsub将仅返回字符串的修改版本。 In your case, I'd use gsub .在你的情况下,我会使用gsub Also, reject(&:nil?) might be replaced with compact , it does the same thing.此外, reject(&:nil?)可能会替换为compact ,它做同样的事情。 And you can call downcase inside the same block where you call gsub .您可以在调用gsub的同一块内调用downcase

asset_types = Company.find(@company_id).asset_types.pluck(:name).compact
asset_types.map do |asset_type|
  asset_type.gsub(/([\^,-_])/, '').downcase
end

UDP UDP

Your regexp /([^,-_])/ means replace all characters that are not , , - or _ .您的正则表达式/([^,-_])/表示替换所有不是, , -_的字符。 See the documentation请参阅文档

If the first character of a character class is a caret (^) the class is inverted: it matches any character except those named.如果字符 class 的第一个字符是插入符号 (^),则 class 反转:它匹配除命名字符之外的任何字符。

To make it work as expected you should escape ^ .要使其按预期工作,您应该转义^ So the regexp will be /([\^,-_])/ .所以正则表达式将是/([\^,-_])/

There is a website where you can play with Ruby's regular expressions.一个网站,您可以在其中使用 Ruby 的正则表达式。

To put it simply, you are getting the error because gsub is only a valid Method in Class: String .简而言之,您会收到错误消息,因为gsub只是Class: String中的有效Method You are attempting to use it in Class: Array .您正在尝试在Class: Array中使用它。

If you want to use gsub on your individual array elements, you must do 2 things:如果你想在你的单个数组元素上使用 gsub,你必须做两件事:

  1. Convert your individual array elements to strings (if they aren't strings already).将您的单个数组元素转换为字符串(如果它们还不是字符串)。
  2. Use gsub on those individual strings在这些单独的字符串上使用gsub

The above can be done any number of ways but those basics should address your core question with getting into some of the other potential issues with your code.以上可以通过多种方式完成,但这些基础知识应该解决您的核心问题,并解决您的代码的其他一些潜在问题。

For what its worth, I would typically use something like this:对于它的价值,我通常会使用这样的东西:

new_array = old_array.map {|element| element.to_s.gsub(*args)}

In fact, you could simply change the last section of your existing code from:事实上,您可以简单地更改现有代码的最后一部分:

....gsub(*args).map(&:downcase)

to:至:

....map {|x| x.to_s.gsub(*args).downcase}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM