Jaysan
Jaysan

Reputation: 43

Trying to remove punctuation without using regex

I am trying to remove punctuation from an array of words without using regular expression. In below eg,

str = ["He,llo!"]

I want:

result # => ["Hello"]

I tried:

alpha_num="abcdefghijklmnopqrstuvwxyz0123456789"
result= str.map do |punc|  
  punc.chars {|ch|alpha_num.include?(ch)}  
end 
p result

But it returns ["He,llo!"] without any change. Can't figure out where the problem is.

Upvotes: 0

Views: 403

Answers (3)

Fabio
Fabio

Reputation: 32445

include? block returns true/false, try use select function to filter illegal characters.

result = str.map {|txt| txt.chars.select {|c| alpha_num.include?(c.downcase)}}
            .map {|chars| chars.join('')}

p result

Upvotes: 3

Cary Swoveland
Cary Swoveland

Reputation: 110725

exclusions = ((32..126).map(&:chr) - [*'a'..'z', *'A'..'Z', *'0'..'9']).join
  #=> " !\"\#$%&'()*+,-./:;<=>?@[\\]^_`{|}~"

arr = ['He,llo!', 'What Ho!']    

arr.map { |word| word.delete(exclusions) }
  #=> ["Hello", "WhatHo"]

If you could use a regular expression and truly only wanted to remove punctuation, you could write the following.

arr.map { |word| word.gsub(/[[:punct:]]/, '') }
  #=> ["Hello", "WhatHo"]

See String#delete. Note that arr is not modified.

Upvotes: 0

Rajagopalan
Rajagopalan

Reputation: 6064

str=["He,llo!"]
alpha_num="abcdefghijklmnopqrstuvwxyz0123456789"

Program

v=[]<<str.map do |x|
  x.chars.map do |c|
    alpha_num.chars.map.include?(c.downcase) ? c : nil
  end
end.flatten.compact.join

p v

Output

["Hello"]

Upvotes: 0

Related Questions