Method to front capitalized words

时间:2016-02-03 02:37:14

标签: ruby

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.

3 个答案:

答案 0 :(得分:7)

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.

答案 1 :(得分:5)

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

答案 2 :(得分:2)

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