4

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.

1
  • 2
    Is there ever a possibility of having float strings "0.12" or even scientific notation "3.4e-10"? Can some strings have multiple lines in them? Commented Oct 18, 2012 at 17:14

4 Answers 4

5

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"] 
Sign up to request clarification or add additional context in comments.

3 Comments

There's also reject { |w| w !~ /\D/ } if you don't mind triple negatives (reject, doesn't match, not digit).
@muistooshort In that case you can use select instead of reject. ;)
But then you're stuck with the anchors again and you don't get to make everyone question the difference between genius and insanity :)
4
s = ["lorem", "ipsum", "1734", "dolor", "1", "301", "et", "4102", "92"]
s.reject{|s| s.match(/^\d+$/) }

Comments

3

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"]

Comments

0

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
    

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.