I have an array with indices 0..n The 0th position is nil. My information starts at position 1. What is a Ruby way of traversing this array and start with position one. Currently what I'm doing is the following:
([email protected]).each do |index|
do something with @vertices[index]
end
I'm building chemical formula names. And to avoid confusion, I want to store a molecule with 1 Carbon atom in @vertices[1]
Use a Hash instead:
@vertices = {
1 => 'Molecule with 1 carbon atom',
2 => 'Molecule with 2 carbon atoms',
5 => 'Molecule with 5 carbon atoms'
}
@vertices.each do |carbon_atoms, molecule|
# do something with molecule
end
I'm unsure why you're starting from index 1, as 0 is standard, but the way I would approach this is either:
@vertices[1..-1].each { |element| do_what_you_planned_on_doing }
or
@vertices.each_with_index do |ele, index|
next if index == 0
do_what_you_planned_on_doing
end
I prefer the first one. It seems more elegant.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With