我正在尝试将大写单词移到句子的前面。我希望得到这个:
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."]
关键是保持词序。
我觉得我很亲近。
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
很想知道其他优雅的解决方案可能是什么。
最佳答案
问题被彻底改变了,使我之前的回答完全错误。现在,答案是:
def capsort(strings)
strings.partition(&/\p{Upper}/.method(:match)).flatten
end
capsort(["a", "This", "test.", "Is"])
# => ["This", "Is", "a", "test."]
我之前的回答是:
def capsort(strings)
strings.sort
end
capsort(["a", "This", "test.", "Is"])
# => ["Is", "This", "a", "test."]
'Z' < 'a' # => true
, 没有什么可做的。
关于ruby - 前面大写单词的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35167539/