Languages and Loops

Before delving into Ruby I dabbled in a few other languages, the primary one being Javascript. In fact, Javascript is the first programming language that I got beyond the most basic syntax in, and so the expressiveness that Ruby has in trying to make things more human-readable wasn’t something that I looked for or expected, or even realized existed in programming to the level that it does. I learned things the Javascript way, and had a lot of fun with it.

Because of my Javascript background, when my Flatiron School batch started learning loops and iteration in Ruby, it just made sense to me. I didn’t really give much thought as to why, until a talk Ashley gave which used the Javascript for loop to explain the magic behind the Ruby times method.

If you were to print out the numbers 0 through 10, Javascript would do:

for (i = 0; i < 11; i++) {
  console.log(i);
}

Ruby would do:

11.times do |i|
  puts i
end

Now, to a lot of people the Ruby way would be readable simply because it's more expressive - the method tells you exactly what you will be doing. Printing i to the console 11 times. But it doesn't tell you at all how it's going to do it. All of that is hidden magic in the deep, dark recesses of Ruby.

The Javascript loop, in contrast, makes you work a little more to see what's going on. When I first was exposed to the JS for loop, I thought it made no sense, but now I'm familiar enough with it that reading and understanding it - both what it does and how it works - is intuitive and natural to me. Even though it isn't using english to describe what the loop does, it tells you the ingredients and instructions, which Ruby doesn't. To break down the JS loop a bit, you're passing the loop three chunks of information. First, you tell it what the counter will start at. Then you give a condition for it to stop at. Finally, you specify what you want the counter to increase by at each iteration.

For me, because I knew the Javascript loop so intuitively, I felt that I understood what was happening in Ruby loops even though the magic was abstracted away. At first it didn't even occur to me that what was happening under the hood may not be clear, because I already knew how this works from knowing Javascript. When it was brought up in class, though, was the first time I realized the extent to which my JS knowledge was helping me understand why things work in Ruby. It was an interesting realization. I think if I didn't already know Javascript learning concepts like how loops work in Ruby would be harder to grasp.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>