Learning Ruby – Day 6

Day 6, How to deal with files and other data streams.

What’s a reliable way to get the last item in an array? ask for the -1 item, i.e. array[-1].
Finally, a logical reason to start arrays at 0 rather than 1 – so we can count backwards.

Looks like the “then” part of an “if…then” statement can come first. As in this example from the book, removing a leading zero from a decimal number.
avg[0,1] = '' if avg[0, 2] == "0."

This will take some getting accustomed to. I’m more familiar with it written this way:

if avg[0,2] == "0."
avg[0,1] == ''

To accommodate When Bad Things Happen, Ruby has a pretty cool construct:

rescue BadThing1Happened
rescue BadThing2Happened

Two cool things here; first – this seems like a simple way to write more readable code – error conditions or otherwise, second – the word “rescue”, makes you feel like a superhero for catching Bad Things. Incentive enough for writing better code.

This post documents my journey through Sam’s Teach Yourself Ruby in 21 days. I’ll be joining Al Abut in his effort to learn Ruby and blog along the way.

2 Replies to “Learning Ruby – Day 6”

  1. Getting the last element of an Array can also be done like [1, 2, 3].last. But what if you need the last two elements? [1, 2, 3].last(2).

Leave a Reply

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