What is the “right” way to iterate through an array in Ruby?

后端 未结 12 1755
盖世英雄少女心
盖世英雄少女心 2020-12-04 04:18

PHP, for all its warts, is pretty good on this count. There\'s no difference between an array and a hash (maybe I\'m naive, but this seems obviously right to me), and to ite

12条回答
  •  猫巷女王i
    2020-12-04 05:10

    This will iterate through all the elements:

    array = [1, 2, 3, 4, 5, 6]
    array.each { |x| puts x }
    

    Prints:

    1
    2
    3
    4
    5
    6
    

    This will iterate through all the elements giving you the value and the index:

    array = ["A", "B", "C"]
    array.each_with_index {|val, index| puts "#{val} => #{index}" }
    

    Prints:

    A => 0
    B => 1
    C => 2
    

    I'm not quite sure from your question which one you are looking for.

提交回复
热议问题