cDitch
cDitch

Reputation: 373

Method to front capitalized words

I am trying to move capitalized words to the front of the sentence. I expect to get this:

capsort(["a", "This", "test.", "Is"])
#=> ["This", "Is", "a", "test."]
capsort(["to", "return", "I" , "something", "Want", "It", "like", "this."])
#=> ["I", "Want", "It", "to", "return", "something", "like", "this."]

The key is maintaining the word order.

I feel like I'm very close.

def capsort(words)
  array_cap = []
  array_lowcase = []
  words.each { |x| x.start_with? ~/[A-Z]/ ? array_cap.push(x) : array_lowcase.push(x) }
  words= array_cap << array_lowcase
end

Curious to see what other elegant solutions might be.

Upvotes: 1

Views: 105

Answers (3)

Tim Jasko
Tim Jasko

Reputation: 1542

def capsort(words)
    caps = words.select{ |x| x =~ /^[A-Z]/ }
    lows = words.select{ |x| x !~ /^[A-Z]/ }
    caps.concat(lows)
end

Upvotes: 2

J&#246;rg W Mittag
J&#246;rg W Mittag

Reputation: 369428

The question was changed radically, making my earlier answer completely wrong. Now, the answer is:

def capsort(strings)
  strings.partition(&/\p{Upper}/.method(:match)).flatten
end

capsort(["a", "This", "test.", "Is"])
# => ["This", "Is", "a", "test."]

My earlier answer was:

def capsort(strings)
  strings.sort
end

capsort(["a", "This", "test.", "Is"])
# => ["Is", "This", "a", "test."]

'Z' < 'a' # => true, there's nothing to be done.

Upvotes: 7

sawa
sawa

Reputation: 168081

def capsort(words)
  words.partition{|s| s =~ /\A[A-Z]/}.flatten
end

capsort(["a", "This", "test.", "Is"])
# => ["This", "Is", "a", "test."]
capsort(["to", "return", "I" , "something", "Want", "It", "like", "this."])
# => ["I", "Want", "It", "to", "return", "something", "like", "this."]

Upvotes: 5

Related Questions