<h2class="lecturer">Personal Notes : Philip Osztromok</h2>
<h2class="episodetitle">Part One</h2>
</div>
<article>
<h2class="sectiontitle">Basics</h2>
<p>Ruby does not use any line terminators so the end of a statement is assumed to be the end of a line.</p>
<p>It uses puts to write something to the command line such as</p>
<preclass="inset">
puts "My number is"
puts my_num
puts "Your number is"
puts your_num</pre>
<p>I assume it is possible to in some way use concatenation so that the text and value can be printed with one Ruby statement but</p>
<pclass="inset">puts puts "My number is"+ my_num</p>
<p>does not work. I guess I will find out more about puts later!</p>
<p>Arithmetic seems to be fairly standard. It uses the ** operator for exponentiation so n squared would be n**2 for instance.</p>
<p>When used with integers, division (/) gives you the integer result and discards the remainder and Ruby uses the % percentage sign as the modulo operator to get the remainder.</p>
<p>In addition to puts, we can use print which is very similar. The difference is that puts includes a carriage return whereas print does not.</p>
<p>Note – it is possible to use concatenation with both print and puts provided both (or all) if all of the arguments are strings so something like:</p>
<p>We can use the length method in Ruby to determine the length of a string. Note that although this is a method, unlike some other programming languages (such as Java), we don’t need to put parentheses after the argument name. An example of it’s usage is</p>
<preclass="inset">
name = "Philip Osztromok"
number = name.length
print "The number of characters (including the space) in " + name + " is "
puts number</pre>
<p>Another method we can use with a string is reverse which will, as you might expect, reverse the order of the characters in the string.</p>
<p>We can also use the upcase and downcase methods on a string and again, as expected, these methods will convert the string to all upper case or all lower case respectively.</p>
<h2class="sectiontitle">Comments</h2>
<p>Comments in Ruby come after a # sign and these can cover a full line or can be at the end of a line.</p>
<p>We can also create block comments spanning multiple lines and these start with =begin and stop with =end.</p>
<p>Ruby is a bit more particular with comments than most other languages. Both =begin and =end must be on a line by themselves.</p>
<h2class="sectiontitle">Naming Conventions</h2>
<p>Ruby is quite flexible with naming variables but by convention, these start with a lower-case letter and distinct words are separated by an underscore character.</p>
<p>It is possible to start a variable name with a capital letter, a $ or an @ but by convention these have particular meanings so it is best to avoid them.</p>
<h2class="sectiontitle">Getting input</h2>
<p>We can get input from the user with gets – this method doesn’t need any parameters and will return a string typed at the console terminated when the user presses enter.</p>
<p>In addition, gets adds an extra new line after the input which can give you unnecessary blank lines in the output so you can apply the chomp method to it to remove this extra line.</p>
<p>Typical use of gets will look something like:</p>
<preclass="inset">
print "What's your first name? "
first_name = gets.chomp
puts first_name</pre>
<p>Because of problems with the CodeAcademy interface, I have switched to the video course, Ruby Beginners Programming Training. I have downloaded and installed a Ruby shell and this can be accessed from a command line by typing IRB followed by return.</p>
<p>We can type commands directly into Ruby here and have them interpreted directly such as</p>
<pclass="inset">1 + 2</p>
<p>which of course returns 3 which is printed on the next line.</p>
<p>We can also assign values to variable such as</p>
<pclass="inset">greet = “Hello World!”</p>
<p>and then use a command such as puts greet to display the value of the variable.</p>
<p>We can also create some more complex constructs such as a while loop by typing the following lines and pressing return at the end of each one. Note that when a variable is set, the value is immediately printed to the command line.</p>
<preclass="inset">
i= 0
while i < 10
print i
i += 1
end</pre>
<p>When the final line is entered, the loop executes and outputs, in this case, the numbers 1 to 10 without spaces followed by Nil since nothing is returned.</p>
<p>We can also create a function with the following lines.</p>
<preclass="inset">
def square(n)
return n * n
end</pre>
<p>We can then call that function by typing something like:</p>
<pclass="inset">square(5)</p>
<p>which prints out 25.</p>
<p>We can create a more complicated function with</p>
<preclass="inset">
def sum(num1, num2)
num1 + num2
end</pre>
<p>An interesting point here is that we omitted the return statement and since num1 + num2 returns the result of summing the two numbers, the function still works as expected.</p>
<p>We can rewrite our square function in this way and have it output some text with:</p>
<preclass="inset">
def square(n)
print “The value of n is “
puts n
print “The value of n squared is”
puts n*n
end</pre>
<p>Now if we run this we see the values with appropriate definitions.</p>
<p>Omitting the return statement can give us a problem. Using the above examples, if we type the statement</p>
<pclass="inset">value=sum(1,2)</p>
<p>we can then use this value. For instance, we can type puts value to display the stored total. However,</p>
<pclass="inset">value=square(5)</p>
<p>does not assign a value to value. This may be because there are two implicit returns in the function (puts n and puts n*n). If we add an explicit return (return n*n), it works correctly.</p>
<h2class ="sectiontitle">Back to CodeAdcademy!</h2>
<p>String interpolation. If you have a string, let’s say it is called name and holds the value “Philip” and you want to print it inside a larger string, you might want to print the string “Your name is Philip”, rather than using concatenation, we can use string interpolation. To do this, we include the string in curly braces and put a hash sign in front of it so the command will look something like:</p>
<pclass="inset">puts “Your name is #{name}”</p>
<p>Another method we can use on a string is capitalize which will set the text in that string to upper case for the first letter and lower case for the rest. Usage is:</p>
<pclass="inset">first_name.capitalize</p>
<p>Previously, if we wanted to assign this to a variable, normally this would be the same variable, we used the following syntax:</p>
<p>In other words, we apply the capitalize method to the variable first_name and set the value of first_name to this capitalized value. That is, we are using the method to modify the string.</p>
<p>Ruby provides a convenient shorthand variation for this type of operation:</p>
<pclass="inset">first_name.capitalize!</p>
<p>This produces exactly the same result but is just a little quicker to type. Note that this is not specific to capitalize, we can use this shorthand for other methods such as downcase or upcase and I assume that it is valid for any operation that modifies the value of a string.</p>
<h2class ="sectiontitle">Control Flow in Ruby</h2>
<p>Ruby provides the usual conditional branching with if, elsif (for else if) and else and the syntax for this is:</p>
<preclass="inset">
if condition
do this
else if condition
do this
else
do this
end</pre>
<p>An example of this is:</p>
<preclass="inset">
print "Enter a whole number: "
number = gets.chomp
number = number.to_i
check = number - 1
result = number & check
if result == 0
puts "The number you entered is a power of two"
else
puts "The number you entered is not a power of two"
end</pre>
<p>Note the use of & which is the bitwise and operator. Also, gets returns a string and so this has been converted to an integer with the to_i method (number.to_i! did not work in this instance, perhaps it only works with strings).</p>
<p>I assume that there is a method similar to gets to allow the user to input a number which therefore would not have to be converted</p>
<h2class ="sectiontitle">Unless</h2>
<p>An if statement is usually used to execute some code if a particular condition evaluates to true. However, it is also possible to execute the code if the condition evaluates to false. The distinction is that a condition might be either:</p>
<preclass="inset">
if hungry == true
Or
if hungry != true</pre>
<p>We can also say if hungry == false or if hungry != false, the important point is to understand what the condition is you are evaluating and to use the condition that seems to make more sense. For instance, if you want to execute a statement whenever some condition (let’s call it x) is true it makes more sense to use the condition if x==true than if x==false.</p>
<p>Ruby also provides the keyword unless so rather than testing if a value is false, we can specify that a statement will execute unless some condition is true. Conceptually this is the same as saying execute the statement if the condition is false. Again, however, the real power of the statement is that it allows the code to more closely reflect the logic of the program.</p>
<p>The usage is exactly the same as if:</p>
<preclass="inset">
hungry = false
unless hungry == true
puts "I'm writing Ruby programs!"
else
puts "Time to eat!"
end</pre>
<p>Note – to distinguish between a comparison and an assignment, Ruby uses two equals signs for the comparison operator so for instance if we want to check whether a is equal to b, we might use:</p>
<pclass="inset">if a ==b</p>
<p>The negative of this (that is, if we want to check if a is not equal to b) is != so the usage would be:</p>
<pclass="inset">if a != b</p>
<p>Other comparison operators include</p>
<preclass="inset">
< less than
<= less than or equal to
> greater than
>= greater than or equal to</pre>
<p>The Boolean operators in Ruby are</p>
<preclass="inset">
&& - and
|| - or
! – not</pre>
<h2class ="sectiontitle">Include and gsub</h2>
<p>Ruby has a method called include which we can use to check if a specified string is found inside another string. For instance, if we have a string (which in this example we will call user_input) and we want to check whether or not there is an ‘s’ in that string, we use the command:</p>
<pclass="inset">user_input.include? “s”</p>
<p>So we can effectively find a string or a single character in the string and we might want to replace it. To do that we use gsub!. Note that the exclamation mark is part of the syntax. After the exclamation mark, we put a pair of parentheses which includes two parameters, the string we want to find and the replacement string. The original string is enclosed in a pair of /s and the replacement string is enclosed in quote marks.</p>
<p>For instance, if we want to find any s in the string user_input and replace it with ‘th’, we do this with:</p>
<pclass="inset">user_input.gsub!(/s/, “th”)</p>
<h2class ="sectiontitle">Looping</h2>
<p>A while loop is pretty straightforward in Ruby. It starts with the word while followed by a condition. We then have the line(s) of code to be executed as part of the loop and an end statement to show where the loop ends.</p>
<p>For instance:</p>
<preclass="inset">
counter = 1
while counter < 11
puts counter
counter = counter + 1
end</pre>
<p>Ruby has another type of loop which is similar to while and is called the until loop where the loop iterates until the specified condition is met.</p>
<preclass="inset">
counter = 1
until counter = 10
puts counter
counter = counter + 1
end</pre>
<p>This is not really a different type of loop but it allows us to be more explicit in our description of the terminating condition.</p>
<p>In addition to =, Ruby includes several other assignment operators:</p>
<preclass="inset">
+=
-=
*=
/*</pre>
<p>These take a variable, perform some arithmetical operation and put the new value back into the variable. For instance, we used counter = counter + 1 to increment the value of counter. We could also have used counter += 1 which has the same effect.</p>
<p>To generalise this:</p>
<pclass="inset">variable o= n</p>
<p>where o is some arithmetical operator (+, -, * or %) and n is some numerical value. This will take the value of variable and perform the arithmetical operation on it and the numerical value n and store the result back in variable.</p>
<p>We saw this in the above example with:</p>
<pclass="inset">counter += 1</p>
<p>which takes the value of counter, adds 1 to it and then stores the increased value back in counter – in short it adds 1 to counter.</p>
<p>If we wanted to multiply the value of counter by 10, we could do this with:</p>
<pclass="inset">counter = counter * 10</p>
<p>or</p>
<pclass="inset">counter *= 10</p>
<p>Note that Ruby does not support increment operators such as ++ or --.</p>
<h2class ="sectiontitle">The For Loop</h2>
<p>Like the while loop, the for loop n Ruby is quite straightforward. It starts with a for statement followed by the name of a control variable and a range to iterate over.</p>
<p>For instance:</p>
<preclass="inset">
for num in 1...10
puts num
end</pre>
<p>Note that the terminal condition is not completely clear. This code snippet implies that the numbers 1 to 10 will be printed out but in fact only the numbers 1 to 9 are printed.</p>
<p>We effectively have a starting condition of num=1, the for loop takes care of incrementing this value after each iteration and the terminating condition is num = 10. This might appear to contradict the previous statement about the fact that the loop prints numbers up to 9. However, this is because when we specified the number range as 1…10, we used three dots and this instructs the loop to go up to but not include the number 10.</p>
<p>If we replace 1…10 with 1..10 (2 dots), this effectively means to go up to and include the value 10.</p>
<p>We could therefore re-write our loop as following if we want the code to print all the numbers from 1 to 10.</p>
<preclass="inset">
for num in 1..10
puts num
end</pre>
<h2class="sectiontitle">The Iterator</h2>
<p>There is another way to loop over a block of code in Ruby and that is to use an iterator. A very simple example of this is:</p>
<pclass="inset">loop {print”Hello World”}</p>
<p>This is a very simple loop structure and it assumes that the programmer will take care of the control variable. There is no control variable in the above example and this gives us an infinite loop.</p>
<p>Note that in Ruby, the curly braces are generally interchangeable with the keywords do and end (to start and end a block of code). So we could re-write the above loop as:</p>
<preclass="inset">
loop do
print “Hello World”
end</pre>
<p>A more sensible example of loop is as follows:</p>
<preclass="inset">
i=0
loop do
i +=1
print {#i}
break if i > 5
end</pre>
<p>Note that in this example we have used the keyword break to exit the loop when a pre-determined condition is met.</p>
<h2class="sectiontitle">Next</h2>
<p>In previous examples, we have seen various techniques to ensure that at some point we break out of a loop thereby avoiding an infinite loop. The keyword next allows us to break out of an iteration but it does not break out of the loop, it simply skips on to the next iteration.</p>
<p>To demonstrate this, let’s say we have a loop that counts down from 20 to 0 and we want to print the value of the control variable in any iteration if it is an even number. If it is an odd number, we simply skip on to the next iteration.</p>
<p>It is important to ensure that the next statement is put in the right place. That is, we must ensure any code that is to be executed in every iteration is placed before the next statement and any code which we want to skip is placed after it.</p>
<p>To show how important this is, let’s assume that the statement to increment the control variable is placed after next. When the variable reaches a certain value, the next condition will be met and the loop will move on to the next iteration. However, since we have skipped the increment to the control variable, this will still have the same value and this also applies to any subsequent iteration and we will have an infinite loop.</p>
<p>Perhaps just as seriously, the only values for which the loop executes the code we want will be those that appear before the next condition is met for the first time. In our example where we count down from 20 to 0 and print the even numbers only, the loop will print 20, count down to 19, activate the next clause to skip to the next iteration without printing 19 and then skip again since the control variable still equals 19 and then again and so on ad infinitum.</p>
<p>Let’s see how this loop is implemented correctly:</p>
<preclass="inset">
i = 20
loop do
i -= 1
next if i % 2 == 1
print {#i}
break if i <= 0
end</pre>
<h2class="sectiontitle">Arrays</h2>
<p>Like many other programming languages, an array is defined in Ruby by placing a collection of values in square brackets such as:</p>
<pclass="inset">my_array = [1,2,3,4,5]</p>
<p>We can access any element of the array using the index value of the element, also in square brackets so the first element would be specified as:</p>
<pclass="inset">my_array[0]</p>
<p>Note that we count from zero so if we have n elements in the array, the last element is:</p>
<pclass="inset">my_array[n-1]</p>
<p>Ruby also provides a convenient way to iterate through the elements of an array by using the each method on that array.</p>
<p>The syntax for each is</p>
<preclass="inset">
each do |x|
code
end</pre>
<p>where x is a variable to be used in the code and code is, of course, the code to be executed for each value.</p>
<p>To make this clearer, assume that we have an array called simply array which contains the values [1,2,3,4,5] and we want to add 10 to each value and print the result. The code to achieve this is:</p>
<preclass="inset">
array.each do |x|
x += 10
print x
end</pre>
<h1class=>Times</h1>
<p>Going back to the for loop, typically this type of structure is used when you want to execute some code a set number of times. Ruby provides a more convenient and compact way to do this via the times method.</p>
<p>Let’s say we want to ask a user to input their age and name and print out their name once for each year of their age. The code to do this would be something like:</p>
<preclass="inset">
print “Please enter your age to the nearest year: ”