Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby array starting at 1 [duplicate]

Tags:

ruby

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
like image 917
Mike Glaz Avatar asked Apr 23 '26 17:04

Mike Glaz


2 Answers

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
like image 193
Stefan Avatar answered Apr 28 '26 12:04

Stefan


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.

like image 42
David Avatar answered Apr 28 '26 14:04

David



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!