PHP尽管有缺点,但在这方面做得很好。数组和哈希之间没有区别(也许我很天真,但这对我来说显然是正确的),要遍历其中任何一个,你都可以这样做
foreach (array/hash as $key => $value)
在Ruby中,有很多方法可以做到这一点:
array.length.times do |i|
end
array.each
array.each_index
for i in array
哈希更有意义,因为我总是用
hash.each do |key, value|
为什么我不能对数组这样做?如果我只想记住一个方法,我想我可以使用each_index(因为它使索引和值都可用),但是必须使用array[index]而不是value是很烦人的。
哦,对了,我忘了array。each_with_index。然而,这个很糟糕,因为它是|值,键|和哈希。每个键|,值|!这不是很疯狂吗?
试图对数组和哈希始终如一地做同样的事情可能只是代码的味道,但是,冒着被打上令人讨厌的半猴子补丁的风险,如果您正在寻找一致的行为,这能做到吗?:
class Hash
def each_pairwise
self.each { | x, y |
yield [x, y]
}
end
end
class Array
def each_pairwise
self.each_with_index { | x, y |
yield [y, x]
}
end
end
["a","b","c"].each_pairwise { |x,y|
puts "#{x} => #{y}"
}
{"a" => "Aardvark","b" => "Bogle","c" => "Catastrophe"}.each_pairwise { |x,y|
puts "#{x} => #{y}"
}
这将遍历所有元素:
array = [1, 2, 3, 4, 5, 6]
array.each { |x| puts x }
# Output:
1
2
3
4
5
6
这将遍历所有给你值和索引的元素:
array = ["A", "B", "C"]
array.each_with_index {|val, index| puts "#{val} => #{index}" }
# Output:
A => 0
B => 1
C => 2
从你的问题我不太确定你在找哪一个。
试图对数组和哈希始终如一地做同样的事情可能只是代码的味道,但是,冒着被打上令人讨厌的半猴子补丁的风险,如果您正在寻找一致的行为,这能做到吗?:
class Hash
def each_pairwise
self.each { | x, y |
yield [x, y]
}
end
end
class Array
def each_pairwise
self.each_with_index { | x, y |
yield [y, x]
}
end
end
["a","b","c"].each_pairwise { |x,y|
puts "#{x} => #{y}"
}
{"a" => "Aardvark","b" => "Bogle","c" => "Catastrophe"}.each_pairwise { |x,y|
puts "#{x} => #{y}"
}