Ruby is a Object Oriented language so it’s no less than intuitive to have classes. The following code block shows the basic syntax of a Ruby class.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
|
We have a Class variable, @@classCount
. This is equivalent to the keyword static
in Java. There’s an Instance variable @instanceCount
.
Then there are the methods. initialize
is the constructor used when you run Counter.new
, icIncrement
is an instance method, while self.ccIncrement
is a class method – called with Counter.ccIncrement
.
Finally to_s
is the conversion of the class to a String, just like toString()
.
1 2 3 4 5 6 7 8 9 10 11 12 |
|
Variable Scope
Scope-wise, there are 5 different types of variables in Ruby and they are simply differentiated by the first character of their name.
- $: Global
- @@: Class
- @: Instance
- [A-Z]: Constant
- [a-z_]: Local
Note that Constants can still be changed. The interpreter will simply issue a warning that that is the case, but the value assigning will proceed.
1 2 3 4 5 |
|
Dynamic Typing
Ruby doesn’t care what class an object is, as long as it does what you want it to do. If it quacks like a duck, it is a duck.
I’ve prepared the 3 files below already. To see them, checkout the branch git checkout dynamic_typing
. This code is based on the code snippets in the Ruby Cookbook which was based on Ruby 1.8
1 2 3 4 5 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
|
1 2 3 |
|
And back to irb. This time, run it with irb -I .
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
|
Unfortunately it seems like function parameters can no longer be given a type so the example isn’t the most clear. This is what it looks like in the book.
1 2 3 4 5 6 7 |
|
Duck Punching
So what if our ducks (Man) don’t quack? Then we punch them until it does.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
|
Just to be clear, we can also do the same to the Woman class.
1 2 3 4 5 6 7 8 9 10 11 |
|