07-18-2023, 06:28 PM
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.
- `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.