【问题标题】:How can I convert an array into a string that lists each item next to its position in the array?如何将数组转换为字符串,在数组中的位置旁边列出每个项目?
【发布时间】:2015-06-17 20:27:09
【问题描述】:

我想要一个数组... teams = ["Cowboys", "Heat", "Blue Devils"]

...并将其转换为字符串... # => "1. Cowboys 2. Heat 3. Blue Devils"

...并使用字符串插值将其与另一个字符串连接起来。

# => "My three favorite teams: 1. Cowboys 2. Heat 3. Blue Devils"

【问题讨论】:

    标签: arrays ruby string string-interpolation


    【解决方案1】:

    使用each_with_index:

    teams = ["Cowboys", "Heat", "Blue Devils"]
    numbered = teams.each_with_index.map { |team, i| "#{i + 1}. #{team}" }.join(" ")
    # => "1. Cowboys 2. Heat 3. Blue Devils"
    

    然后你可以插值:

    fave_teams = "My #{teams.size} favorite teams: #{numbered}"
    

    each_with_index 添加每个元素的位置并返回一个枚举器,您可以使用块映射该枚举器。该块接收每个项目及其索引。

    【讨论】:

      【解决方案2】:
      teams.map.with_index(1) do |t, i|
        "#{ i }. #{ t }"
      end.join( ' ' )
      

      【讨论】:

        猜你喜欢
        • 2015-10-09
        • 1970-01-01
        • 1970-01-01
        • 2019-05-11
        • 2015-11-11
        • 2017-12-01
        • 2021-12-13
        • 2015-03-10
        • 1970-01-01
        相关资源
        最近更新 更多