In Ruby we can add comments to our code in two ways
- Single line comments
- Multi-line comments
For single line comments, we use # before the comment to be added.
For eg: #this is a comment
For multi-line comment; we use =begin at the start and =end at the end.
I want to add
Note: There should be no space between = and begin/end
Everything in Ruby is an object and has specific built-in abilities knows as “methods”.
For eg strings have built-in methods that can tell you the length of the string, reverse it, capitalize it and much more.
It returns the length of the string.
Ruby will output =>> 6
This method reverse the string that we provide.
Ruby will output => ahseyA
.upcase & .downcase
These two methods can be used to change the case of a string.
As the name suggests, .upcase would change the entire string to uppercase and .downcase would change the entire string to the lower case.
puts “Ayesha”.downcase would give output =>> ayesha
puts “Ayesha”.upcase would give output =>> AYESHA
In Ruby, if we have to print something on the output screen we have two options:
The difference between the two is that the puts (“put string”) is slightly different from print in such a way that it adds a new line in the output after what you print.
No parenthesis or semicolons are needed.
There are 6 arithetic operators which we would discuss at this point
- Addition +
- Subtraction –
- Multiplication *
- Division /
- Exponentiation **
- Modulo %
All are self-explanatory but for the beginners: Exponentiation raises one number (the base) to the power of the other (the exponent).
For eg: 2 ** 3 is 8 [ Basically it means 2*2*2 ]
Coming to Modulus: it returns the remainder of division.
For eg: 17 % 5 would be 2
Programming in Ruby
The benefits of using Ruby for web development:
- High level language so its easy to understand
- Object oriented
- Easy to use
Starting with “how to code using Ruby”; for now we discuss only the 3 mainly used data types:
Note: Do not use quotation marks ” ” for the boolean values otherwise Ruby will think it to be a string value.
Lets do a small exercise here that shows how to declare variables and assign them values.
my_number = 25
my_boolean = true
Declaring variables in Ruby is quite simple. Just write the name and assign it a value using the = operator
For eg: Lets set a variable my_num to the value 150
To do so we simply do as follows: