Ruby
Yet another scripting language ?. Mainly, i need this now for vagrant which uses ruby style configuration files.
Also the devhints.io sources use ruby.
hello
classes
Classes are defined like below, and each of the variables has it's specific notation :
- local variable, not visible outside the class start with _
- instance variables start with @
- class variables (static)start with @@
- global variable start with $
- a symbol starts with : , symbols are immutable
methods
methods are define with : def... end, so for a working example :
| def | |
|---|---|
So creation is done with new, but called as a method of the class.
To show an example of class variables, this example maintains a count of Customer objects created:
The output:
Alternatively when you run display_details :
| details | |
|---|---|
you get :
This displays the way to get the value of a variable of constant, just put an # in front of it.
constants
These simply begin with an uppercase letter, so let's just take the trusted convention of all caps :
| all caps | |
|---|---|
Note that we need the {} around the constant, otherwise it will print #VAR1
arrays
| arrays | |
|---|---|
Straightforward in the declaration, except the trailing comma. which is just discarded.
ranges
Here an example will suffice i think:
hashes
| hashes | |
|---|---|
So, the || can contain multiple values.
closures
These are called code blocks in ruby, but they are closures so why not call them that. They have the general form :
do ... end
Forms :
- do ... end
- do || ... end
- do |arg_list| ... end
- { ... }
- { || ... }
- { |arg_list| ... }
The closure is not executed as it is encountered, but ruby remembers the context as it is encountered, with local variables, current objects etc. And then enters the method. Once inside the method, you can call the block using the yield keyword with a value. Only then will the block be executed with the former context in place.