simonrohrbach
simonrohrbach

Reputation: 522

Remove numbers from array of strings

I have an array that looks like this:

["lorem", "ipsum", "1734", "dolor", "1", "301", "et", "4102", "92"]

Is there a way to remove all the numbers in the array, even though they're stored as strings, so that I'd be left with this:

["lorem", "ipsum", "dolor", "et"]

Thanks for any hints.

Upvotes: 4

Views: 1875

Answers (4)

Pradip
Pradip

Reputation: 1537

One way I can say is: REGEX match

  1. Loop though all the items
  2. Then use this:

    txt='Your string'
    
    re1='(\\d+)'    # Integer Number 1
    
    re=(re1)
    m=Regexp.new(re,Regexp::IGNORECASE);
    if m.match(txt)
        int1=m.match(txt)[1];
        # REMOVE THE ITEM HERE
    end
    

Upvotes: 0

Phrogz
Phrogz

Reputation: 303234

If all your strings are just integers, @Simone's answer will work nicely.

If you need to check for all numeric representations (floats and scientific notation) then you can:

s = %w[ foo 134 0.2 3e-3 bar ]
s.reject!{ |str| Float(str) rescue false }
p s
#=> ["foo", "bar"]

Upvotes: 3

Simone Carletti
Simone Carletti

Reputation: 176402

Use a regexp pattern

s = ["lorem", "ipsum", "1734", "dolor", "1", "301", "et", "4102", "92"]
s.reject { |l| l =~ /\A\d+\z/ }
# => ["lorem", "ipsum", "dolor", "et"] 

Upvotes: 5

ChuckE
ChuckE

Reputation: 5688

s = ["lorem", "ipsum", "1734", "dolor", "1", "301", "et", "4102", "92"]
s.reject{|s| s.match(/^\d+$/) }

Upvotes: 4

Related Questions