Basic Syntax
Declaring Variable Names
In ruby, when declaring variable names always use snake_case, not camelCase. Each time you need to name something that requires multiple words, separate those words using underscores _
, and make the whole title lowercase. Names should never start or contain uppercase letters.
Comments
In ruby a single line comment looks like this:
A multiple line comment looks like this:
Symbols
Symbols are primarily used as hash keys, or to reference method names. Once a symbol is created, it can not be changed, and only one copy of a symbol can exist at any given time. There can not be multiple symbols with the same value. Symbols look like this: :symbol
. They have a colon, and then are followed by a name.
Prints, Puts, Return, & Yield
Print:
The print command takes whatever instructions you give it, and puts it on the screen, on the same line.
Output:
Puts:
The puts command creates a new line for each thing that you have it print.
Output:
Return:
The return command just returns the value of something. If you don’t tell ruby what to return, it will always return the last expression in the method code block.
In the example above, we defined a method called double
. Inside the method, we return n * 2
. We then set a variable output
which is equal to double(6)
. with the argument of 6
. We then add two to output
, and we puts
the variable output
. If you don’t tell ruby what to return, it will always return the result of the last expression in the method code block.
Yield:
The yield command allows for methods (that don’t have the capability already) to accept a block of code. Methods that accept blocks have a way of transferring control from the method to the block and back to the method again. You can build this into methods by using the yield command.
Output:
You can also pass parameters to the yield command.
Output:
The yield_name method
is defined with one parameter, name
. On line 8, we call the yield_name
method and supply the argument "Eric"
for the name
parameter. Since yield_name
has a yield
statement, we will also need to supply a block. Inside the method, on line 2, we first puts
an introductory statement. Then we yield
to the block and pass in "Kim"
. In the block, n
is now equal to "Kim"
and we puts
out "My name is Kim."
Back in the method, we puts
out that we are in between the yields. Then we yield
to the block again. This time, we pass in "Eric"
which we stored in the name
parameter. In the block, n
is now equal to "Eric"
and we puts
out "My name is Eric."
Finally, we puts
out a closing statement.
Last updated