Friday, February 17, 2017

Methods, Classes, and Variables

Ruby is an object-oriented language, and thus has very simple class and method support.  In addition, it has a wide range of variables which have different properties.  Here's an example of a rather simple class:



This particular class has instance methods (methods which pertain to one instance of a class), a class method (akin to a static method in Java), an instance variable (which pertains to one instance of a class), and a class variable (akin to a static variable in Java).

In addition, it references two other variables, one global and one local.  Global variables can be accessed anywhere, while local ones are tied to their specific area.  Here, they act in similar fashions, but they are fundamentally different.

When you take this class and add some code like this:



Then you can see that it will print a large amount of statements.  First, it instantiates a RandomClass with a value of one, prints out the variable, prints out a toString type thing, sets the variable to something different, and then prints out that toString substitutes again.

Then, it prints the local variable, sets the local to the return of the static method, and then prints it again, before it creates a temporary instance with value 20, and then prints it.

After this, it sets the global variable to 18, prints out the value of the static method, creates a new class using the global as the value, and then prints the toString.

Finally, it prints the class variable.  The result is this:



This is exactly what you would expect, with the only unique, Ruby-esque twists being the symbols before the variable names to designate their purpose and the "::" instead of the "." most other languages use to call a static (or any kind) of variable.

The three people whose blogs I commented on are:

Julian Kastelic, whose blog is https://perlnecklace.wordpress.com/,
Joseph Pernick, whose blog is http://cs270joepernick.blogspot.com/,
and Caroline Marcus, whose blog is https://swift359.wordpress.com/.

No comments:

Post a Comment