Just finished up Chapter 4 of Beginning Ruby, which walks you through creating a basic application that pulls information from a separate text file and performs a few calculations based on the contents of the file. This was a good exercise, because up until now I'd just been coding information directly into the file itself, and coding so that Ruby can pull information from elsewhere is obviously more versatile and useful.
But here's a question. It seems like it makes sense to separate logic from output. So that this bit of code:
word_count = text.split.length
puts "#{word_count} words"
paragraph_count = text.split(/\n\n/).length
puts "#{paragraph_count} paragraphs"
Should really be written as:
word_count = text.split.length
paragraph_count = text.split(/\n\n/).length
puts "#{word_count} words"
puts "#{paragraph_count} paragraphs"
Seems like doing it this way makes it easier to go back and edit code later, since the two won't be mixed together. I'm sure there are exceptions to this rule, however.
On a side note, the program I wrote scanned a text file and displayed information based on the text file. But it kept throwing in some junk characters, adding a "\92" after every sentence. So I went back through my code, trying to figure out what I'd messed up. The real culprit was the text I'd copied and pasted from the internet, and clearing the formatting of the text file got rid of the junk characters. Awesome!
I'd like to thank everyone who's given me advice or commented on my blog or otherwise encouraged me to learn Ruby. I'm having a great time so far. I think about what I know about Ruby today and how it was completely unfathomable to me a week ago, and then I think about what I'll know next week that is completely unfathomable to me right now and I can't help but get excited.
No comments:
Post a Comment