P
Pat Maddox
Is there a way to get each element of an array, as well the index of
that element? Something like
a =3D %w[foo bar]
a.each { |val, index| .... } # val =3D> 'foo', index =3D> 0
If there's no way to do that, is it better to use each_index and then
access the array?
a.each_index do |i|
puts i
puts a
end
vs finding the index after you have the element
a.each do |val|
puts a.index(val)
puts val
end
Intuitively I'd think the second way may be a bit slower than the
first, because it has to search through the array for the element,
rather than accessing the index directly. Maybe not though...I'd just
like a bit of explanation on this.
Thanks,
Pat
that element? Something like
a =3D %w[foo bar]
a.each { |val, index| .... } # val =3D> 'foo', index =3D> 0
If there's no way to do that, is it better to use each_index and then
access the array?
a.each_index do |i|
puts i
puts a
end
vs finding the index after you have the element
a.each do |val|
puts a.index(val)
puts val
end
Intuitively I'd think the second way may be a bit slower than the
first, because it has to search through the array for the element,
rather than accessing the index directly. Maybe not though...I'd just
like a bit of explanation on this.
Thanks,
Pat