Ruby Tutorial #2

There are very few programming fundamentals but an infinite way of using and expressing them.

I will start with two basic types – Strings and Integers.

A string is an ordered sequence of zero or more characters.
An integer is any whole natural number.

Ruby is a weakly typed language meaning that you don’t need to predetermine a variables type at declaration, rather it is dynamically set (and reset) at assignment.

message = “hello world” #string
puts message
puts message.class

message = 42 #integer/fixnum
puts message
puts message.class

The key parts of the above script are:
message: a variable
puts: prints to the console
#: a comment. Anything following the # is ignored.
.class: is a method of Object (message in this case)

Don’t worry if all these terms don’t make complete sense yet.

Some other methods to try out are:

puts message.reverse
puts message.upcase
puts message.length
puts message[0..4]

Strings can be changed and manipulated. The plus sign is concatenation eg.

message = “hello world”
message = message[0..5] + ‘mum’
puts message

Appending a ! on the end will change the contents of the variable in place.

message = “Hello Mum”
puts message
puts message

Ruby treats everything as an object. For example

puts “hi mum”.length

And you can chain methods together

puts “Hello muM”.upcase.swapcase