【问题标题】:Calling an array, having it not only display each item but also their position within the array调用一个数组,让它不仅显示每个项目,还显示它们在数组中的位置
【发布时间】:2017-12-31 02:04:22
【问题描述】:

试图想出一种方法,根据数组中的项目数为数组中的项目分配特定位置。举个例子,如果我面前有一排排的 10 把椅子,根据第一个走进来的人,我会给他们分配第一把椅子第二把椅子,依此类推(基本上是数组的作用)。但是,每次我向数组中添加一个项目时,我都希望该项目(当调用数组时)在最后显示它的位置。

array = ["item1 is in position 1", "item2 is in position 2"...]

到目前为止,这是我的想法。顺便说一句,它被设计为一种简单的方法,根据它们在数组中的位置为每个项目分配一个数字。

def keeping_track(array) new_array = [] array.each {|item| new_array << "#{item} is currently in position ____"} return new_array end

____ 区域是我迷路的地方,我对 ruby​​ 也很陌生。我认为有一种方法可以调用数组中的项目位置,加 1 然后将该数字转换回整数,但我只是不确定从哪里开始。提前感谢您的帮助。

【问题讨论】:

    标签: arrays ruby


    【解决方案1】:

    这可能是另一种方法,使用地图。

    def keeping_track(array)
    
      array.each_index.map {|item| "#{array[item]} is currently in position #{item + 1}"}
    
    end
    

    【讨论】:

    【解决方案2】:

    使用each_with_index

     array.each_with_index {|item, position| new_array << "#{item} is currently in position #{position}"}
    

    这将从 0 开始对位置进行编号,如果您想将第一个位置显示为位置 1,那么您可以 #{position + 1}

    【讨论】:

    • 如果 OP 希望第一个位置为 1,那么 each.with_index(1) 也是一个选项。
    • 这正是我想要的,感谢您的快速回复。
    • @SagarPandya 真的吗?那是什么版本推出的?
    • Enumerator#with_index 已经存在了一段时间,至少从 1.9.1 开始。
    猜你喜欢
    • 2019-10-20
    • 1970-01-01
    • 1970-01-01
    • 2015-12-21
    • 1970-01-01
    • 2021-02-17
    • 1970-01-01
    • 2015-01-12
    相关资源
    最近更新 更多