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
CodePudding user response:
As it was said arrays don't respond to gsub!. An array is a collection of items that you might process. To achieve what you want you should call gsub on each item. Notice the difference between gsub! and gsub methods. gsub! will modify a string itself and might return nil whereas gsub will just return a modified version of a string. In your case, I'd use gsub. Also, reject(&:nil?) might be replaced with compact, it does the same thing. And you can call downcase inside the same block where you call gsub.
asset_types = Company.find(@company_id).asset_types.pluck(:name).compact
asset_types.map do |asset_type|
asset_type.gsub(/([\^,-_])/, '').downcase
end
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.
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.
CodePudding user response:
To put it simply without getting into other potential issues with your code, you are getting the error because gsub is only a valid Method in Class: String. You are attempting to use it in Class: Array.
If you want to use gsub on your individual array elements, you must do 2 things:
- Convert your individual array elements to strings (if they aren't strings already).
- Use
gsubon those individual strings
The above can be done any number of ways but those basics should directly address your core question.
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}
