ruby - 前面大写单词的方法

标签 ruby

我正在尝试将大写单词移到句子的前面。我希望得到这个:

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/

相关文章:

ruby-on-rails - Rails 中确定两个(或更多)给定 URL(作为字符串或哈希选项)是否相等的最佳方法是什么?

Ruby 哨兵循环未按预期工作(七周七种语言)

ruby - 如何让 ruby​​ 打印完整的回溯而不是截断的回溯?

ruby - 使用 Nokogiri 获取节点的兄弟节点

ruby-on-rails - ruby 弃用警告 : You are using the old router DSL which will be removed in Rails 3. 1

arrays - 这是 Ruby 中 Array.fill 方法的错误吗?

ruby-on-rails - "configuration"是保留名称吗?

Ruby 在映射时放置定期进度消息

ruby - Ruby 中的 Array#sort 为什么这么快?

mysql - 获取类型为 `text` 的字段