For 2023 (and 2024 ...) - we are now fully retired from IT training. We have made many, many friends over 25 years of teaching about Python, Tcl, Perl, PHP, Lua, Java, C and C++ - and MySQL, Linux and Solaris/SunOS too. Our training notes are now very much out of date, but due to upward compatability most of our examples remain operational and even relevant ad you are welcome to make us if them "as seen" and at your own risk.
Lisa and I (Graham) now live in what was our training centre in Melksham - happy to meet with former delegates here - but do check ahead before coming round. We are far from inactive - rather, enjoying the times that we are retired but still healthy enough in mind and body to be active!
I am also active in many other area and still look after a lot of web sites - you can find an index ((here)) |

Well House Consultants
You are on the site of
Well House Consultants
who provide
Open Source Training Courses
and business
hotel accommodation. You are welcome to browse and use
our resources subject to our copyright statement and to add in links from your pages to ours.
Other subject areas - resources
Java Resources
Well House Manor Resources
Perl Resources
Python Resources
PHP Resources
Object Orientation and General topics
MySQL Resources
Linux / LAMP / Tomcat Resources
Well House Consultants Resources
Extras Resources
C and C++ Resources
Ruby Resources
Tcl/Tk Resources
Web and Intranet Resources
|
Ruby module R104
Control Structures
Exercises, examples and other material relating to training module R104. This topic is presented on public courses Learning to program in Ruby, Ruby Programming
Background Conditional statements, loops, and
functions you would expect. Exceptions,
iterators and methods may be new to you. And
you'll need to know how to write conditions
too. Related technical and longer articles Converting to Ruby? Start hereConditionals, loops, and iterators in Ruby
Articles and tips on this subject | updated | 4674 | Alternating valuses / flip-flop / toggle - example in Ruby If you want to alternate the value of a variable, here's two ways you can do it in Ruby - answers to a question during this week's Ruby Course
# Too clever?
t = 0
(1..20).each do
puts (((t=(t+1)%2)==0) ? "yes" : "no")
end
#Â better?
t ... | 2016-05-17 | 4504 | Where does Ruby load modules from, and how to load from current directory All (scripting) languages allow you to load code from other supporting source files, using keywords like use, load, source and include. In Ruby, the most common way to load other code is to require it - and if you use the require method you'll load in code from another file which will be assumed to ... | 2015-06-03 | 4503 | Separating your code for easier testing, understanding and re-use; example in Ruby You don't want to write the same piece of program twice. Nor do you want to have to call in the technical experts on a particular topic to work on general code. So you should separate your code (whatever language you're using) into named blocks, where the named blocks each represents an element that's ... | 2015-06-03 | 4402 | Finding sum, minimum, maximum and average in Python (and Ruby) A fresh example (in Python) from today's "learning to program in" course ... finding the number, sum, minimum and maximum of a series of numbers typed in. See [here].
We start off with zero for the count and sum to date, but we do not initialise the minimum or the maximum as we don't know what they ... | 2015-01-19 | 4370 | Conditionals, loops and methods in Ruby - a primer with simple examples Continuing 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 ... | 2014-12-30 | 4323 | Learning to program - Loop statements such as while If your program always ran each statement just once (indeed skipping over statements which were in blocks in false conditions) it would run very quickly and would have little use. You couldn't (for example) run a program which went through a whole series of results from a database query and displayed ... | 2014-11-22 | 4322 | Learning to Program - the conditional statement (if) Every language has some sort of conditional statement. That's a way of looking at some sort of setting or status in the program and performing some sort of action based on that setting or status.
such statements take the form ...
if {some sort of condition is true} then {run a group of ... | 2014-11-22 (longer) | 3200 | How a for loop works Java, Perl and other languages Java, Perl, PHP, Ruby, C, C++, Tcl and many other languages support a "for" loop construct.
When your program enters the top of the loop, it performs the first statement in the brackets ... in this Perl example, that's to initialise the $now variable to 1. It then evaluates the expression given as ... | 2014-02-02 | 3620 | Finding the total, average, minimum and maximum in a program There are a number of programming techniques which the experienced coder takes for granted, but which aren't necessarily intuitive for the newcomer. Call them "design techniques" or "design patterns" that need to be learned, if you want some fashionable buzzwords.
• To produce the sum of a stream ... | 2012-10-08 | 3769 | Muttable v immutable and implications - Ruby A muttable object is one which can be changed in situ, and an immutable object is one that can't be changed in situ - if you want a modified version, you have to build it afresh, using whichever components you require from the orginal. And if the original's not required, you can then scrap it.
There's ... | 2012-06-23 | 3397 | Does a for loop evaluate its end condition once, or on every iteration? All the languages that we teach have a for loop or the equivalent, which is a clean way of repeating a block of code with a rising or falling index number. It's used in many circumstances - for example in iterating through the months of the year (for m goes from 1 to 12) of in stepping through all ... | 2012-04-15 | 3619 | Ruby v Perl - a comparison example One of the popular exercises I set on our Perl courses goes something like ...
Write a program to ask the user to enter four numbers each between the value of 1 and 6. If the user enters a number below 1 or over 6, ask him to enter that number again. If the user enters the word END, stop reading numbers.
Print ... | 2012-02-25 | 3422 | Assigning values to variables within other statements - Ruby In Ruby, and in Perl too, you can use assignments within other statements and in so doing perform two distinct actions in one line of code. Here's what I mean (using irb - interactive Ruby):
>> j = 16
=> 16
>> print "The value is #{k=j} at the moment"
The ... | 2011-09-07 | 3254 | Multiple inputs, multiple out, ruby functions Has it ever struck you as curious that in many languages, you can pass as many parameters into a function as you like, but you can only return one? Well - that's many language not all - in Ruby you can return a whole series of values in a comma separated list, and place each into its own variable.
You ... | 2011-04-20 | 3253 | Is this number between? Does this list include? - Ruby There's often a requirement in a program to see if one value is between two others, and in most languages you'll write that as as double condition:
if (n >= 5 && n <= 8) printf("Yesssss!\n");
in C or C++, for example.
Some languages give you further options / methods you ... | 2011-04-19 | 3156 | Splitting data reading code from data processing code - Ruby An iterator (a.k.a. generator in Python) is a function which returns its results as it calculates them, rather than building them up into a larger structure to return all at once when the function is completed. So where you have a big flow of incoming data, you can handle it as it arrives rather than ... | 2011-02-10 | 3158 | Ruby training - some fresh examples for string handling applications Ruby's a great language. No - let me rephrase that "Ruby's a fantastic language" ... for many tasks such as "data munging" - handling / manipulating large flows of data, in all sorts of ways. But in my training role, I come across far more people using Ruby on Rails, Selenium and Watir than Ruby for ... | 2011-02-10 | 3159 | Returning multiple values from a function call in various languages - a comparison I've always thought it a bit odd that you call a function with any number of parameters, and yet it returns a single value; in Java, C or C++ you declare a return type (void if there is not to be anything returned) and you are then constrained by that specification. There are, of course, other ways ... | 2011-02-10 | 962 | Breaking a loop - Ruby and other languages When you're in a loop there are occasions you want to say get me our of this loop NOW, or "I'm done with the current iteration. And those are the 'classic' break and continue statements from C, C++ and Java. Languages like Perl changed break to last and continue to next ... and added a redo that asks ... | 2011-01-29 | 2975 | Why do I need brackets in Ruby ... or Perl, Python, C or Java In many languages, you're required to put brackets around the boolean condition in your if and while statements, and around parameters you're passing to functions. And it becomes the natural way of coding for programmers in languages like Java, C and C++. But when you think about it, those brackets ... | 2010-09-29 | 2892 | Alternative loops and conditionals in Ruby and Perl Ruby gets a lot from Perl - including its eclecticness in having a wide variety of alternative ways of doing similar things - and no more so than in loops and conditionals. Not only do you have an if but also an unless. Not only do you have a while but also an until. And not only can you write these ... | 2010-07-30 | 2711 | For loop - checked once, or evety time? Ruby v Perl comparison and contrast Although may aspects of Ruby are inherited (in a non-OO way!) from Perl, there are some distinct differences too; a classic for loop in Perl has its end condition checked every time around the loop, but a Ruby for loop sets up an iterator at the start, so that if something changes within the loop evaluation ... | 2010-04-08 | 2619 | Passing code to procedures and yield in Ruby If you want to pass a block of code into a Ruby procedure, you can do so by passing in the code to a variable who's name you start with an & in the procedure definition; you can then run that code using the .call method on the received object. In some ways this is an indirect reference - in Ruby ... | 2010-02-02 | 2471 | A short form of if ... then ... else There are so many times you want to say "if ... then ... else" to do no more than choose between the word "is" and "are", to say "child" or "children", or to say "may" or "may not" in your output. Using an if statement for that's a lot of code for a little job.
In most of the languages we teach (Perl, ... | 2009-10-23 | 2287 | Learning to program in Ruby - examples of the programming basics We so often overlook the basics of programming, and yet they are so fundamental to good code - understanding things like how widely variables can be seen (also known as variable scope), what happens when you divide two numbers (do you get a decimal result or is the remainder thrown away), and how do ... | 2009-07-15 | 1904 | Ruby, Perl, Linux, MySQL - some training notes We have just come to the end of a solid 12 days of training ... and we are just getting ready for the next week, with delegates arriving this evening. There's a lot going on behind the scenes, even over this weekend, with the hotel to be prepared as well as the training course. (Picture - our clean ... | 2008-11-24 (longest) | 1887 | Ruby Programming Course - Saturday and Sunday We're so busy during the week at the moment that I'm running an extra Ruby Course this weekend. The main use of Ruby is within "Ruby on Rails", but our course concentrates on the language itself and so it's suitable for people who are using RSpec, cucumber and Watir as well as Rails.
Here are some ... | 2008-11-16 | 1891 | Ruby to access web services If you want to use a Ruby program to access an RSS feed (or some other XML or HTML data), you can start with the standard Net::HTTP module ... full (working, tested) example here. That example "just" uses a Get method to get an RSS feed of the latest posts to the First Great Western Coffee Shop Forum ... | 2008-11-16 | 1870 | What to do with a huge crop of apples Last year, you had a good crop of apples on your tree .... what did you do with them? Make apple pies for all the neighbours! How?
• You collect all the apples and bring them into the kitchen.
• You prepare the apples ready for the pies.
• You make the pastry and apple pies.
• You ... | 2008-11-04 | 1738 | Clean code, jump free (Example in Lua) The "goto" statement - in languages that still support it - is regarded with disdain by Computer Scientists as it makes for spaghetti code - hard to follow and going all over the place!
In some ways, loop controls "break" and "continue" ("last", "next" and "redo" in Perl; "next", "redo", "retry" and ... | 2008-08-07 | 1696 | Saying NOT in Perl, PHP, Python, Lua ... "Isn't there one standard way to say NOT?" asked one of my delegates on today's course - and it's an excellent question. But the answer to a question about a negative subject is itself in the negative - no, there isn't just a single way!
In fact .. I can think of no fewer that 12 ways!
• 1. ! ... | 2008-07-05 | 1587 | Some Ruby programming examples from our course I was giving a Public Ruby Course to a small group at the end of last week ... and having a small group gave me the opportunity to write some demonstrations in front of them. I have now tidied these up and have pleasure in presenting to more Ruby demonstrations:
Ruby's BEGIN block
The compact method ... | 2008-03-21 | 1582 | Ruby, C, Java and more - getting out of loops break and continue statements have been available for loop control for many years, and others functionallity has been added such as Perl's redo. From today's Ruby Course, here's a table that compares these loop controls in Ruby to similar commands in the other languages that I have been discussing ... | 2008-03-19 | 1220 | for loop - how it works (Perl, PHP, Java, C, etc) When writing a program, you'll often want to repeat a block of code, counting up through a table or performing a block of code with an input value (loop counter) that goes up 1, 2, 3, 4 etc.
You COULD do this using a while loop, but this means you have to specify each of
• how to start (initialise) ... | 2007-06-07 | 1163 | A better alternative to cutting and pasting code If you're new to coding, you'll be so concerned to be writing code that works that you may not take a look at coding technique. Your nose will be so close to the grindstone as you work that you won't take the time to look and ask "Do I need to keep grinding anyway?"
If you find yourself writing a piece ... | 2007-04-26 | 995 | Ruby's case - no break It has always struck me that switch statements in languages like C, PHP, Tcl and Java are very longwinded and clumsy, with a need for blocks and blocks, and every case having to end with a break (or equivalent) to stop multiple cases being run via a drop-through. I can understand why they were written ... | 2006-12-17 | 985 | Equality in Ruby - == eql? and equal? The == comparison checks whether two values are equal
eql? checks if two values are equal and of the same type
equal? checks if two things are one and the same object.
How do I remember which is which ... The longer the operator, the more restrictive the test it performs
Example:
irb(main):013:0> ... | 2006-12-14 (short) | 960 | 1st, 2nd, 3rd revisited in Ruby I've been updating some of my Ruby examples today (as one does on a Saturday!) and I thought back to the post I made yesteday concerning 1st, 2nd, 3rd, etc in Python.
Ruby has a case statement, even though Ruby is a bit of a cross between Python and Perl, neither of which supports the structure. Historically, ... | 2006-12-04 |
Examples from our training material
amp_pass | Passing code blocks to procedures | collect | for and each loops over an array. Also sorting | condi.rb | Example of Ruby conditionals | csep | Separation of repeated and specialist code | ctors.rb | Comparators - what is true? | cx | between and include | d2.6 | if elsif elsif else | d2.7 | while, until and for loops - comparison | dbu | Variable and method of same name | ddd.rb | Iterators in Ruby | dice | Throwing dice, summing, printing average | dm.rb | Defining and using a method | dm2.rb | Method, parameter, optional parameter | dm3.rb | Dynamic redefinition of a method | doubleret | multiple returns and unlimited parameters | ex | Class exercise - ordering lunches | exx | Putting common code in a name block (function) | five | Some unusual conditionals and loops | howcome | Multiple actions in a single statement | ident | mutable object (array) | lazyops.rb | Lazy operators | llen | Methods and default parameter | llen2 | calculating default parameters | llen3 | Default a parameter to nil | loop.rb | Loop in ruby - run until it breaks | loopy.rb | Loop structures in Ruby | mi | redefine a method in Ruby | moretrains | Requiring a module from the current directory | mwpar | In Ruby you can redefine a function ... | rmi | Multiple return values from a function | rubber | ? : conditional operator in Ruby | scram.rb | Break redo next and retry | sid | Loop and conditional - exercise | tog | toggling a variable - ruby | u1 | How many teams needed? | vcx | Quick first validation example | yetan | immutable object (integer) | yrb | yield (co-routines / generator) |
Background information
Some modules are available for download as a sample of our material or under an Open Training Notes License for free download from [here].
Topics covered in this module
Blocks and the if statement. Writing conditions. Comparative, boolean and range operators. Conditionals - if, unless, case, etc. Loops - while, for in, until, etc. break, next, retry and redo. defined? and ternary operators.
Complete learning
If you are looking for a complete course and not just a information on a single subject, visit our Listing and schedule page.
Well House Consultants specialise in training courses in
Ruby,
Lua,
Python,
Perl,
PHP, and
MySQL. We run
Private Courses throughout the UK (and beyond for longer courses), and
Public Courses at our training centre in Melksham, Wiltshire, England.
It's surprisingly cost effective to come on our public courses -
even if you live in a different
country or continent to us.
We have a technical library of over 700 books on the subjects on which we teach.
These books are available for reference at our training centre.
|
|
|