Ruby Beauty – Iteration with an Index

April 5, 2010 • Damien White

I just love how expressive and clean Ruby’s syntax is. How often do you need to iterate over a collection and get a count as well? That sort of code is ugly in something like C#, but in Ruby:

people = %w{Dave Bill Mike Mark John} # Simple collection of names
people.each_with_index { |name, index| puts "#{index}: #{name}" }

And that displays:

0: Dave
1: Bill
2: Mike
3: Mark
4: John

each_with_index – simple and elegant.

And what’s the C# version of something like this look like? Blah :)

Posted in ruby and tagged with Ruby

Damien White

I am a software architect with over 16 years of experience. I simply love coding! I have a driving passion for computers and software development, and a thirst for knowledge that just cannot be quenched. I'm happy to share what I know in my quest to learn as much as possible. I focus most of my time on web development using Ruby on Rails, Ember.js, and ASP.NET MVC.

comments powered by Disqus