Home > Blockchain >  Remove a group on strings from an object in ruby
Remove a group on strings from an object in ruby

Time:05-31

So, I have the following

removed_caps = self.user.caps.reject { |c| c == 'test' || c == 'test1'}

I want to have test and test1 as configs so that I can add to these in the future.

so something like:

caps_to_remove = ENV['BLACK_LIST']
split_caps_to_remove = caps_to_remove.split(' ')
puts split_caps_to_remove -->>> ["test", "test1"]

How do I incorporate split_caps_to_remove in the original code?

Thanks.

CodePudding user response:

You could change your code to:

removed_caps = self.user.caps.reject { |c| split_caps_to_remove.include?(c) } 

CodePudding user response:

Use Fixed-String Methods

Assuming you have some variables defined as in the example below, then you can use String#delete or String#delete! as a faster way to remove your unwanted characters. Consider:

caps = ENV['BLACKLIST']='TE'
str1, str2 = 'TEST', 'TEST1'

[str1, str2].map { _1.delete caps }
#=> ["S", "S1"]

Fewer methods in a chain are often faster, and String methods that operate on a fixed String are often and order of magnitude faster Regexp-related methods like #gsub or iterating over a collection.

See Also

You didn't provide your actual input or calling code, but in newer Ruby versions (including 3.1.2) there are some other related methods (some with bang methods, which are both useful and faster if you aren't using frozen strings) that may also help:

  • Related