【问题标题】:How to sort a string in ruby? [duplicate]如何在 ruby​​ 中对字符串进行排序? [复制]
【发布时间】:2012-03-24 22:51:02
【问题描述】:

可能重复:
How to sort a string's characters alphabetically?

假设有一个简单的字符串 str = "bacd" 我想对其进行排序以使结果包含 结果 = "abcd"

我如何在 Ruby 中做到这一点?

【问题讨论】:

    标签: ruby


    【解决方案1】:

    又好又简单:

    str = 'bacd'
    p str.split('').sort.join # => "abcd"
    

    【讨论】:

    • 稍微好一点:str.chars.sort.join
    【解决方案2】:

    Tokland 的评论非常好,值得一个完整的回答:

    str.chars.sort.join
    

    这适用于 Ruby 1.8 和 1.9。

    您可以找到 Ruby 文档here

    【讨论】:

      猜你喜欢
      • 2017-08-11
      • 1970-01-01
      • 1970-01-01
      • 2013-05-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-04
      • 2014-10-23
      相关资源
      最近更新 更多