Basics

Ruby does not use any line terminators so the end of a statement is assumed to be the end of a line.

It uses puts to write something to the command line such as

	puts "My number is"
	puts my_num
	puts "Your number is"
	puts your_num

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

puts puts "My number is"+ my_num

does not work. I guess I will find out more about puts later!

Arithmetic seems to be fairly standard. It uses the ** operator for exponentiation so n squared would be n**2 for instance.

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.

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.

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:

puts "Philip " + "Osztromok" + " is the greatest!!"

is perfectly fine.

String Methods

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

	name = "Philip Osztromok"
	number = name.length
	print "The number of characters (including the space) in " + name + " is "
	puts number

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.

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.

Comments

Comments in Ruby come after a # sign and these can cover a full line or can be at the end of a line.

We can also create block comments spanning multiple lines and these start with =begin and stop with =end.

Ruby is a bit more particular with comments than most other languages. Both =begin and =end must be on a line by themselves.

Naming Conventions

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.

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.

Getting input

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.

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.

Typical use of gets will look something like:

	print "What's your first name? "
	first_name = gets.chomp
	puts first_name

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.

We can type commands directly into Ruby here and have them interpreted directly such as

1 + 2

which of course returns 3 which is printed on the next line.

We can also assign values to variable such as

greet = “Hello World!”

and then use a command such as puts greet to display the value of the variable.

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.

	i= 0
	while i < 10
	print i
		i += 1
	end

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.

We can also create a function with the following lines.

	def square(n)
		return n * n
	end

We can then call that function by typing something like:

square(5)

which prints out 25.

We can create a more complicated function with

	def sum(num1, num2)
		num1 + num2
	end

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.

We can rewrite our square function in this way and have it output some text with:

	def square(n)
		print “The value of n is “
		puts n
		print “The value of n squared is”
		puts n*n
	end

Now if we run this we see the values with appropriate definitions.

Omitting the return statement can give us a problem. Using the above examples, if we type the statement

value=sum(1,2)

we can then use this value. For instance, we can type puts value to display the stored total. However,

value=square(5)

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.

Back to CodeAdcademy!

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:

puts “Your name is #{name}”

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:

first_name.capitalize

Previously, if we wanted to assign this to a variable, normally this would be the same variable, we used the following syntax:

first_name = first_name.capitalize

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.

Ruby provides a convenient shorthand variation for this type of operation:

first_name.capitalize!

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.

Control Flow in Ruby

Ruby provides the usual conditional branching with if, elsif (for else if) and else and the syntax for this is:

	if condition
		do this
	else if condition
		do this
	else
		do this
	end

An example of this is:

	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

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).

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

Unless

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:

	if hungry == true 
		Or
	if hungry != true

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.

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.

The usage is exactly the same as if:

	hungry = false

	unless hungry == true
	 puts "I'm writing Ruby programs!"
	else
	 puts "Time to eat!"
	end

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:

if a ==b

The negative of this (that is, if we want to check if a is not equal to b) is != so the usage would be:

if a != b

Other comparison operators include

	< less than
	<= less than or equal to
	> greater than
	>= greater than or equal to

The Boolean operators in Ruby are

	&& - and
	|| - or
	! – not

Include and gsub

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:

user_input.include? “s”

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.

For instance, if we want to find any s in the string user_input and replace it with ‘th’, we do this with:

user_input.gsub!(/s/, “th”)

Looping

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.

For instance:

	counter = 1
	while counter < 11
	puts counter
	counter = counter + 1
	end

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.

	counter = 1
	until counter = 10
	puts counter
	counter = counter + 1
	end

This is not really a different type of loop but it allows us to be more explicit in our description of the terminating condition.

Assignment Operators

In addition to =, Ruby includes several other assignment operators:

	+=
	-=
	*=
	/*

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.

To generalise this:

variable o= n

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.

We saw this in the above example with:

counter += 1

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.

If we wanted to multiply the value of counter by 10, we could do this with:

counter = counter * 10

or

counter *= 10

Note that Ruby does not support increment operators such as ++ or --.

The For Loop

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.

For instance:

	for num in 1...10
	 puts num
	end

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.

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.

If we replace 1…10 with 1..10 (2 dots), this effectively means to go up to and include the value 10.

We could therefore re-write our loop as following if we want the code to print all the numbers from 1 to 10.

	for num in 1..10
	puts num
	end

The Iterator

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:

loop {print”Hello World”}

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.

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:

	loop do
	print “Hello World”
	end

A more sensible example of loop is as follows:

	i=0
	loop do
	i +=1
		print {#i}
		break if i > 5
	end

Note that in this example we have used the keyword break to exit the loop when a pre-determined condition is met.

Next

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.

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.

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.

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.

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.

Let’s see how this loop is implemented correctly:

	i = 20
	loop do
	i -= 1
		next if i % 2 == 1
		print {#i}
		break if i <= 0
	end

Arrays

Like many other programming languages, an array is defined in Ruby by placing a collection of values in square brackets such as:

my_array = [1,2,3,4,5]

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:

my_array[0]

Note that we count from zero so if we have n elements in the array, the last element is:

my_array[n-1]

Ruby also provides a convenient way to iterate through the elements of an array by using the each method on that array.

The syntax for each is

	each do |x|
		code
	end

where x is a variable to be used in the code and code is, of course, the code to be executed for each value.

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:

	array.each do |x|
	x += 10
		print x
	end

Times

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.

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:

	print “Please enter your age to the nearest year: ”
	age = gets.chomp
	age = age.to_i
	print “Please enter your name: “
	name = gets.chomp
	age.times { print name }