什么是"右QUOT;这样,通过在Ruby中数组循环? [英] What is the "right" way to iterate through an array in Ruby?
问题描述
PHP,其所有疣,是pretty这个算不错。有一个数组和哈希(也许我幼稚,但是这似乎很明显我的权利)没有什么区别,并可通过你只是做迭代
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 iterate through either you just do
foreach (array/hash as $key => $value)
在Ruby中有一堆的方式做这样的事情:
In Ruby there are a bunch of ways to do this sort of thing:
array.length.times do |i|
end
array.each
array.each_index
for i in array
哈希更有意义,因为我只是总是用
Hashes make more sense, since I just always use
hash.each do |key, value|
为什么我不能数组做到这一点?如果我要记住只有一个方法,我想我可以使用 each_index
(因为它使双方指数和价值提供),但它很烦人要做数组[索引]
,而不是仅仅值
。
Why can't I do this for arrays? If I want to remember just one method, I guess I can use each_index
(since it makes both the index and value available), but it's annoying to have to do array[index]
instead of just value
.
哦,对了,我忘了 array.each_with_index
。然而,这一次吮吸,因为它会 |价值,关键|
和 hash.each
进入 |键,值|
!这是不是疯了?
Oh right, I forgot about array.each_with_index
. However, this one sucks because it goes |value, key|
and hash.each
goes |key, value|
! Is this not insane?
推荐答案
这将通过所有的元素迭代:
This will iterate through all the elements:
array = [1, 2, 3, 4, 5, 6]
array.each { |x| puts x }
打印:
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}" }
打印:
A => 0
B => 1
C => 2
我不是从你的问题哪一个你正在寻找非常肯定。
I'm not quite sure from your question which one you are looking for.
这篇关于什么是"右QUOT;这样,通过在Ruby中数组循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!