简体   繁体   中英

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! . 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! andgsub 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.

To put it simply, 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:

  1. Convert your individual array elements to strings (if they aren't strings already).
  2. Use gsub on those individual strings

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}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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