代码之家  ›  专栏  ›  技术社区  ›  Bob.

在Ruby的每个do循环中使用计数器变量还有别的选择吗?

  •  4
  • Bob.  · 技术社区  · 15 年前

    我正在用Ruby从数组中输出一个项目列表。我需要输出数组中每个项的位置以及值。我以为我很聪明,在循环遍历数组时使用值的索引,而不是设置一个临时计数器变量,但是当我有一个包含重复项的数组时,我被烧掉了。见下文。。。

    array = ["a","b","c","a"]
    array.each do |letter|
     puts "Position: #{array.index(letter)} - Letter: #{letter}"
    end
    
    # Position: 0 - Letter: a
    # Position: 1 - Letter: b
    # Position: 2 - Letter: c
    # Position: 0 - Letter: a    # Oops! That's not the position of that item.
    

    下面是生成所需输出的最有效方法,还是有更好的方法将计数器变量赋值保持在每个do循环中?

    array = ["a","b","c","a"]
    counter = 0
    array.each do |letter|
      puts "Position: #{counter} - Letter: #{letter}"
      counter += 1
    end
    
    # Position: 0 - Letter: a
    # Position: 1 - Letter: b
    # Position: 2 - Letter: c
    # Position: 3 - Letter: a
    
    3 回复  |  直到 15 年前
        1
  •  11
  •   Nakilon earlonrails    15 年前
    array = ["a","b","c","a"]
    array.each_with_index do |letter,i|
      puts "Position: #{i} - Letter: #{letter}"
    end
    

    还有,如果你需要的话 map 方法,您可以使用 .with_index 修饰语

    ["a","b","c","a"].map.with_index { |e,i| [e,i] }
    
    => [["a", 0], ["b", 1], ["c", 2], ["a", 3]]
    
        2
  •  3
  •   Sébastien Le Callonnec    15 年前

    只需使用 each_with_index :

     a.each_with_index{ |o,i| puts "position #{i} - letter #{o}" }
    
        3
  •  1
  •   cHao    15 年前

    times 东西。:)

    array.length.times do |i|
      puts "Position: #{i} - Letter: #{array[i]}"
    end
    

    注意,我只是在学Ruby——这可能是邪恶的东西。

    推荐文章