Conditionals, loops and methods in Ruby - a primer with simple examples
Archive - Originally posted on "The Horse's Mouth" - 2014-12-29 12:11:14 - Graham EllisContinuing with my basic Ruby update - a lot of examples on control structures at [this link].
Conditionals in Ruby include if, unless and case (the equivalent of a switch statement. It's been argued that for a strongly object oriented language a "switch" type structure is not needed, and indeed encourages coding away from the language paradigm. However, in the case of ruby one has been provided (compare and contrast to Python!). See example of each syntax [here]. Ruby also supports "lazy operators" which are in effect conditionals - see an example [here].
In any condition, the question "what does equality mean" may arise, and in ruby there are four ways of asking the question:
== - equal in value
=== - Used to test equality within a when clause of a case statement
.eql? - same type AND equal in value
.equal? - the same object
See example [here]
loops come in number of varients too - see examples of for and each loops [here], and note the double and triple dot operators:
1..20 - 1 to 20, including 20
1...20 - 1 to 20, excluding (stopping short of) 20
There's a while loop - write it forward (the conventional way [here]) or backward as shown [here] and even a loop statement without a condition that you must break out of - [here] ... see a real use of it [here] when I keep re-prompting the user for input until he enters a valid reply. If you want the negative condition, replace "while" with "until".
named blocks of code are know as "methods" and are defined using a def keyword. There's a first simple example [here] and one showing an optional (defaulted) parameter [here]. Methods can even be redefined "on the fly" - not always a good thing, but useful in some circumstances - see [here].
As well as methods with conventional return statements, Ruby supports generators which will yield a series of results in succession - see [here] for an example of the definition and use of such a function.
I'm starting the new year with a private Ruby course ... and open for further bookings right through the year. There's one week available in January, nothing in February (sorry - fully booked), and one week in May. March, April and June onwards are fairly open at the moment. Public course are provisionally set to start on 20th April, 13th July and 19th October ... the latter dates may change, but we work on the basis that once we get even just a single booking for the course they're fixed and guaranteed to run. See [here] for course details