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

后端 未结 12 1765
盖世英雄少女心
盖世英雄少女心 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条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-04 05:19

    I think there is no one right way. There are a lot of different ways to iterate, and each has its own niche.

    • each is sufficient for many usages, since I don't often care about the indexes.
    • each_ with _index acts like Hash#each - you get the value and the index.
    • each_index - just the indexes. I don't use this one often. Equivalent to "length.times".
    • map is another way to iterate, useful when you want to transform one array into another.
    • select is the iterator to use when you want to choose a subset.
    • inject is useful for generating sums or products, or collecting a single result.

    It may seem like a lot to remember, but don't worry, you can get by without knowing all of them. But as you start to learn and use the different methods, your code will become cleaner and clearer, and you'll be on your way to Ruby mastery.

提交回复
热议问题