July 01, 2015

Throwing a die - exercise in Ruby

One of the exercises I often set on our open source programming courses is to ask delegates to write a program to read (from the user) up to 6 values thrown on a die, and report on the total and average. And I ask the delegates to check for errors, and allow the user to enter a special code to say they want to stop (finish early). The exercise does wonders in checking people's early understainding of the language being taught, it's input / output, conditionals and loops.

Here is one I wrote in Ruby earlier this week. You'll note:
redo to jump back to the top of a loop and restart the current iteration (as opposed to next which would take you on to the next iteration
break to get you out of a loop
• The use of ? and : as a shortform of "if ... else"
• the .to_i method to convert a string (in our example) to an integer
• use of .. to give a range that's inclusive of both ends - ... dives a range which excludes the end point
• Use of #{......} to embed the value of an expression in a text string
• If a statement is clearly incomplete on one line,the Ruby compiler / interpretter assumes it carries on onto the next line, but if it could be complete, that assumption isn't made

Posted by gje at 03:39 PM | Comments (0)
More about Graham Ellis of Well House Consultants
Useful link: Ruby training
Related topics: via article database

Well House Consultants Ltd.
Copyright 2015