Ruby has many built in shortcuts for allowing access to instance variables. In most languages (Java, PHP ) you typically define your Class properties/variables then would go about defining getter / setter methods for each variable. In Ruby they have defined attribute modifiers to easily define the getter setter methods without having to write them each out.

attr_accessor

The attr_accessor modifier is used to define both getter and setter methods for instance variable(s) of a class.

class Car
    attr_accessor :year, :make, :model
end

In the above example we have defined a Car object that has 3 properties year, make, and model. In addition we have made it so that we could read and write to each of those properties.

car = Car.new
car.year = 2010
car.make = "Toyota"
car.model = "Prius"
 
puts car.year

attr_reader & attr_writer

In some cases you will want to only allow properties to be read or write and not both in those cases you would use attr_reader for read only access and attr_writer for write only access.

class Car
    attr_reader :year
    attr_writer :owner
end

In this case you would be able to set the @owner property but not read it directly and for @year you would be able to get the property but not set it.

These handy attribute modifiers allow you to quickly define the getter setter methods in your class without taking the time or code to write up each method individually. However be aware that not all properties should be read/writable directly.

, , , ,

Ruby is definitely a loose language. All classes in the language even core classes like the base Object are open and can be modified at any time. Also Ruby in addition to allowing you to do object inheritance allows you to include and extend modules within your Classes.

Open Classes

What open classes means is that you are free to modify and change any class at any time during the execution of your script or application. In addition any changes made will affect existing instances of that class. Lets take a quick look at modifying the main Object class.

class Object 
    def myMethod
        puts "this is my new method on the base Object Class"
    end
end

By adding this method to the main Object it now means that every Class that extends from the Base Object e.g. everything now has this function. In essence if my had a myClass object that we already instantiated after the above code runs you would be able to call the myMethod function for it and it would output the text.

Include and Extend Classes with Modules

The include and extend keywords allow you add module functions and constants to the specified class and it’s instances. To start off lets first discuss what a Module is in Ruby.

The Basics of Modules

A Module is similar to a class with the exception that they can have no instances or subclasses. Instead what they are used for is for defining a collection of constants or static methods. For example the Math module in Ruby defines functions for performing basic calculations like square root and constants like Pi. To define a module you simply use the module keyword.

module MyModule
    def myMethod
        puts "this is my method in my module"
    end
end

Including Modules in Classes

You can add methods of a Module to an instance of a class by including it in the class by the include keyword.

class SampleClass
    include MyModule
end

Having included our module we will find that the methods defined in the module are now added to the Class and any instances of the Class will be able to call the methods. The methods will not be accessible from the Class itself.

obj = SampleClass.new
obj.myMethod  // outputs: this is my method in my module
SampleClass.myMethod // NoMethodError

Extending Modules in Classes

Conversely to Includes, Extending Modules makes the methods available at the class level and not for instances.

class AnotherClass
    extend MyModule
end
 
obj = SampleClass.new
obj.myMethod  // NoMethodError
SampleClass.myMethod // outputs: this is my method in my module

Like I said in the beginning Ruby is a very loose language. It allows you at any moment to modify or overwrite Classes, Methods, and Constants of any Object including those objects that are core to the language. However the include and extend functionality allows you to use the mixin technique to implementing multiple inheritance without supporting true multiple inheritance.

, , , , , ,

Taking a break from diving into further details of Classes and Objects, I have detoured into taking a closer look at some of the naming conventions that are used in the Ruby programming language. In particular we are going to look at Constants and local, global, instance, and class variables.

Constants

In Ruby you define a constant by having it start with an uppercase character. Yes, it is that simple if you want a constant whether at the class level or on the procedural level simply start your naming with an upper case character and it is defined as a constant.

SecretNum = 13987
 
class ConstantClass
    Pass = "PASS"
    Fail = "FAIL"
end

To access the constants of a class you would simply type {ClassName::ConstantName} while non class constants are simply called like a variable.

puts SecretNum
puts ConstantClass::Pass

However as it turns out Ruby let’s you reassign the value of defined constants at any time, yes they say that you should only assign a value to it once but they let you change it. Why would you use these “constants” if they can be changed at any time? The second strange thing is that if you have a Constant defined Ruby still lets you define a method with the same name.

def SecretNum()
  puts 666
end

Now you have both a constant and a method with the same name. Where if you leave out the parenthesis the Constant is used by if you add them the method is called.

puts SecretNum    // outputs 13987
puts SecretNum() // outputs 666

Again why? Needless to say it is good practice to name your methods starting with a lower case, but if you are defining your language so that Capitals are reserved for defining constants you should enforce that either methods all start with a lowercase character or that a constant with the same name doesn’t exist.

Variables

Variables are identified by their first and or second character, in which they define the scope of where it can be utilized.

Global Variables

Global Variables are identified by starting with the $ character. These variables can be set or read from anywhere within your program even in classes and methods.

$globVar = 8
puts $globVar  // outputs 8

Local Variables

A local variable is simply a named variable. It can be accessed anywhere in the current scope it was defined. If it is defined in a method it can only be used in that method.

def testMethod( var = "testing 1 2 3" )
    puts var
end

Instance Variables

An instance Variable has it’s scope confined to the object it belongs to and begins with the @ character. These can be accessed by methods belonging to the object or set and read by their name if they are defined as accessible.

class MyClass
    def doSomething( var ) 
        @something = var
    end
    def doSomethingElse( ) 
        puts @something
    end
end

Class Variables

Perhaps the most confusing of all variables is the Class Variable. These variables are recognized by their names starting with @@. These variables can be accessed by a class and its inheriting sub classes. So if you change the variables value in a sub class the base class’s value is also changed. I’m not going to go into any further detail on this as of this moment I do not see any reason why you would ever use a Class Variable as if you needed to I don’t see why you wouldn’t just use a constant.

Those are the basics on the Naming Convention used by Ruby to identify the scope of variables and constants. Pretty basic with a few strange twists added in, once again I find myself thinking that Ruby is popular simply because it lets you do pretty much whatever you want no matter how bad design and code wise it is. However i am trying very hard to keep an open mind and will reserve judgment until my crash course is finished.

, , , , , ,

Processing is an open source programming language that has been around since 2001, and has steadily become a comprehensive alternative to proprietary software for the creation of images, motion graphics and teaching aid to students. This Java based language and environment allows you to quickly and easily create mesmerizing graphics in 2D and 3D that will quickly have you wondering what else you can do.

For a sneak peak at what you can do with Processing simply visit the examples on their official website. For myself I have a couple little projects in mind that i hope I find the time to work on soon. The first being the creation of a script to generate a simple 3D medieval castle out of bricks that the user would be able to rotate and examine via some basic mouse/keyboard interactions. The second being a little app to visualize my Google Analytics data over time for different variables. What fun this will be, now where o where will I find the time to play with this . . .

Resources

, , ,

Previously in Lesson 1 of this Ruby crash course I spoke mainly about getting Ruby setup and some basic differences in the syntax. In this lesson we are going to focus and creating classes and methods in Ruby.

Defining a Method in Ruby

Ruby like PHP is a scripting language. What this means is that you don’t need to create a main run method like you would have to in Java. Instead you simply type your commands and you script will run line by line until it terminates. This allows you define methods of code outside of classes, that can be called globally throughout the script. Lets start right in with a basic example:

def myMethod
    puts "testing"
end

As you can see the def command is used to define methods, with the method name following it. If we wanted to have our method take parameters then we add parenthesis with named variables that can be defaulted to values similarly to PHP, Java, and other programming languages.

def myMethod( param = "value" )
    puts param
end

Calling a Method in Ruby

Now for a bit of oddness. In Ruby you don’t need to add the () parenthesis to a method call instead you simply need to pass the method name. Lets use our previous example to illustrate.

myMethod
 
myMethod()

Both of these commands will cal the method you have created. No offense to anyone but how could typing a method like it was a variable make a language easier to read or understand? It seems to me more that the underlying programmers were lazy and simply decided “I wish I didn’t have to type 2 additional characters to call a method”, Seriously what gives?

Defining an Object

Similar to other programming languages an Object in Ruby is created by use of the class keyword. Similar to a method you specify the name after the keyword and its definition terminates by the end keyword. In a class you then define its variables and methods. Similar to PHP’s __construct methods Ruby defines it’s class constructors with initialize, unlike PHP you can not have your constructor be the same name as the Class’s name. Lets take a look at a sample Class.

class MyClass
    def initialize( user_name, age )
        @user_name = user_name
        @age = age
    end
    def welcome 
        puts "Welcome #{@user_name}"
    end

Looking at the code you may think “Where are the variable definitions?” In Ruby you don’t need to specify variable definitions outside of the initialize method. Instead the use of the @ character before a name defines that variable as an instance variable that will be accessible to all methods of the class. At this point lets just say that Ruby is built on some strong naming conventions that will dictate how you write your code. The second thing you may notice is the use of the #{… } notation, this simply means to output the value of what is inside into the containing string.

Instantiating and utilizing Classes

Now that we have defined our class the next logical step would be to instantiate it and use it in our script. unlike Java and PHP where you use the new command to instantiate an Object, in Ruby the new command is actually a function of the Class. This means that your instantiation of the class would be ClassName.new(params).

obj = MyClass.new( "mdbitz", 26 )

A little different but nothing to cry over. Now that we have our instance of the class we can call it’s methods like normal again remembering that you don’t need to include the parenthesis.

obj.welcome

At this point our user_name and age variables are considered private in that we can not get or set the properties directly. If we want to we have 2 choices we could define getter and setter methods or we could use the attr_accessor keyword that will change it so that we can access the variables directly by its name.

class MyClass
    attr_accessor :user_name
    attr_accessor :age
    def initialize( user_name, age )
        @user_name = user_name
        @age = age
    end
    def welcome 
        puts "Welcome #{@user_name}"
    end

By utilizing attr_accessor the variables can be obtained or set by simply calling their names.

puts obj.age
obj.user_name = "testUser"

Interfaces, Abstraction, and Inheritance

In Ruby there are no definitions for Interfaces or Abstract classes or methods. Not sure why they decided to not include these basic design paradigms, but there you have it they do not exist. As for inheritance you can extend classes when defining your classes by following the syntax class ClassName < BaseClassName

class MyNewClass < MyClass
    def getInfo()
        puts "USER_NAME: #{@user_name}\nAGE: #{@age}"
    end
end

Although this is Part 1 of 3 on Ruby Classes and Methods I think it is time to learn a little bit more about the Naming Conventions in Ruby.

, , , , , , , ,