Reputation: 2074
As the tittle suggests, I'd like to get some chars and check if the string as any of them. If I suppose, for example, "!" to be forbidden, then string.replace("",word_with_!)
. How can I check for forbidden chars if forbidden_chars is an array?
forbidden_chars = ["!",",",...]
check ARRAY (it is the string split into an array) for forbidden chars
erase all words with forbidden chars
Could anyone help me please? I just consider searching for the words with the cards and retrieving index as mandatory in the answer please. Thank you very much :)
Upvotes: 0
Views: 62
Reputation: 110675
string = 'I like my coffee strong, with no cream or sugar!'
verboten = '!,'
string.split.select { |s| s.count(verboten).zero? }.join ' '
#=> "I like my coffee with no cream or"
Note this does not preserve the spacing between "I"
and "like"
but if there are no extra spaces in string
it returns a string that has no extra spaces.
Upvotes: 0
Reputation: 36101
string = 'I like my coffee hot, with no sugar!'
forbidden_chars = ['!', ',']
forbidden_chars_pattern = forbidden_chars.map(&Regexp.method(:escape)).join('|')
string.gsub /\S*(#{forbidden_chars_pattern})\S*/, ''
# => "I like my coffee with no "
The idea is to match as many non-white space characters as possible \S*
, followed by any of the forbidden characters (!|,)
, followed by as many non-white space characters as possible again.
The reason we need the Regexp.escape
is for the cases when a forbidden character has special regex meaning (like .
).
Upvotes: 3