Ruby - learning
06/01/2015
cheatsheet
#1. Variable in ruby class
- Local variable: defined inside a method, the usage of local variable in only
inside a method. Prefix of local variable is
_
or[a-z]
. - Instance variable: instance variable is available accross methods and object,
meanwhile, instance variable change from object to object. Prefix of instance
variable is
@
. Instance variable is not shared among its descedants. - Class variable: it belongs to a class and is a characteristic of this class.
Prefix is
@@
. Class variable is share among its descedants(childs). - Global variable: class varaible is not across class, however, global variable
does. The prefix of global variable is
$
. - Constant variable: it’s similar to class variable but it’s constant. Constant varaibles should be in upper case for all letters.
#2. Commenting
- Using
=begin
and=end
- Using
#
#3. Method
#4. Block
- Block must be named after a name of a method (or a function), other while, it does not work. Usage: In a method, there might be an chunk of code which is used many time within the method, the point is that, this chunk of code is not worth making a new function or maybe programmers don’t want to make a function on that chunk (they cannot think a name for that).
- It’s also possible to insert parameters into a block. However, if a function has parameters, I don’t know but there is a error and cannot use block with function which have parameters.
#5. Class
- Class structure
- Initial method
- Getters and setters
#6. Access control: Public, Private, Protected
- Public method: is called by anyone. By default, all methods excepting initialize method are public methods.
- Private method: only class methods can access private methods
- Protected method: is called by class method and its subclass method.
#7.Inheritance, method overriding, operator overloading
- ’<’ is used to indicate inheretent from class to class
- Method overriding: change existing method (parent class) to new method (child class)
- Method overloading: Unlike java, ruby is using dynamic typed language, as a results, it’s impossible to using overriding if depending on variable types. On the other hand, it uses number of parameters to differentiate methods.
8. Loop
a. While loop
b. For loop
#9. Symbols
a. What is this
Symbols in ruby are immutable. Besides this point, it’s a string
. It’s able to print put the value of a symbol in term of string
or integer
b. Implementation Automatic make new method based on the symbols
#10. Hash a. Declare a hash
- Old hash
- New hash
b. Access element
c. Documentation link