Calling an object method in Ruby behind the scenes is actually a message to another object or Message Passing. These can more easily be understood by an example, and for that reason lets look at a basic multiplication script.

3 x 4
</ruby>
As you are aware everything in Ruby is an object, including an integer. Therefor the above operation is really a call to the <em>x</em> method of the integer object.
<pre lang="ruby">
3.x(4)

So far this isn’t very surprising as you are calling the multiplication method of the integer object, however you can call the same method by using the send function passing the method name and parameters. This is called Message Passing.

3.send "x" 4

You may wonder why does it matter. The answer simply put is that you can call any method of an object regardless of its visibility by using the send method. If you want to call a private method of an object that you normally wouldn’t be able to call then by using send you can do so. Ruby has actually tried to restrict this functionality but has been forced to retain it and instead also now provides a public_send method in version 1.9 for those cases you don’t want to access private methods.

Seriously what is the point to having Method Visibility if the underlying fundamentals of the language itself allow developers to bypass them. A ball was definitely dropped somewhere during the creation of the Ruby language.

, , ,

Ruby provides a multitude of methods and structures for iterating or looping through arrays and collections. The most commonly used methods are the basic for and each loops. However there exists other convenience (or code bloat) methods on both arrays and integers to also perform iteration.

The basic FOR loop

The for loop in Ruby functions allows you to iterator through each item in an expression. Where the expression can be an array, collection, or a range.

for i in myArray
    puts "Value of Array index is: #{i}"
end
 
for j in 0..10
    puts j
end

In the second example we are using a Range. In Ruby we can define a range of numbers inclusively by use of the number . . number syntax. The above example will iterate starting at 0 and end at 10.

The Each Statement

The each iterator is similar to the for statement as it loops through the array or hash for every element setting the current element to the defined variable. The one important element to remember is that for hash objects you will need to specify two variables to hold both the key and value.

myArray.each do |var|
    puts i
end
 
myHash.each do |varKey, varValue|
    puts "key: #{varKey} | value: #{varValue}"
end

In addition to the main each statement Ruby has also defined additional methods to iterate over the indexes of a collection each_index and to also return both the element and its index each_with_index. However it is important to remember that the each_with_index function returns the element first then the index.

myArray.each_with_index do |value, index|
    puts "index: #{index} | value: #{value}"
end

Integer iteration with TIMES, UPTO, and DOWNTO

For those that find the for statement cumbersome Ruby has found the need to define the times, upto and downto methods for iterating.

4.times do
    puts "Hello"
end

The times method is used to execute a block of code for the specified number of times. If needed you could also get the current loop index that will start at 0 and go to times – 1.

10.times do |i|
    puts i
end

If you don’t want to iterate starting at 0 for a specific number of times but instead want to iterate over a range then you can use the upto and downto methods. These methods iterate from the integer’s value to the specified value.

1.upto(5) do |i|
    puts i 
end
 
15.downto(10) do |i|
    puts i
end

It is important to remember that the downto and upto method are inclusive so in the example 6 iterations of the code block will occur. Personally I don’t see the reason for these methods, all of the logic that you can perform from it can be created using a simple for loop and why would you need both an upto and downto method why not simply have a to method that could do either depending on if the specified number is larger or smaller. Seriously if you are going to add convenience methods for no other reason then to do so then atleast go all the way.

The Collect and Map functions

While we are on the topic of iteration it is important to touch on the collect and map functions. These functions are used to return a collection after performing the specified code block on each element of the existing collection. As you can tell from the name these functions are most useful in mapping a collection into a new collection with different values.

myArray = ['a','b','c','d']             #=> ["a", "b", "c", "d",]
newArray = myArray.map {|item| item.upcase}      #=> ["A", "B", "C", "D"]

Ruby definitely defines some different methods for performing collection iteration, however no new functionality is presented. Instead we see once again the existence of additional code and functions that add bloat and ambiguity to the core of Ruby. Nearing the end of my self-inflicted crash course, and to date I must say I am not impressed.

, , , , , , , , , , , , ,

Most developers are aware of the Switch statement that compares a variable to specific cases and performs logic based on if it matches the case criteria. In Ruby they decided to implement this as simply a Case statement with when clauses specifying logic to be performed if the when clause is true.

case year
when 2000
    puts "The world was supposed to end this year!"
when 2012
    puts "Now the world is supposed to end this year!"
else
    puts "I wonder what year the world will supposed to end after 2012?"
end

As you can see from the above example it functions the same as in other languages with a slightly different syntax where instead of default you use end and instead of cases you use when

Case statements with multi value When Clauses

In Java, PHP and other programming languages the case statements can fall through so that you can define some logic to occour for multiple values. Ruby is no different in that it too allows you to have multiple values in each when statement the difference is you simply sperate the values by a ,(comma) when defining your when statements.

case year
when 2000, 2012
    puts "The world is going to end!"
else
    puts "Is the world going to end?"
end

Case statement with no value defined

If you simply prefer to write case statements instead of if statements then you can define a case statement that has no value and instead can specify the comparison logic in each when clause.

aString = "testing"
 
case 
when aString="testing"
    puts "What are you testing."
else 
    puts "This is for real everyone!"
end

The Case statement in Ruby breaks no new ground however it does provide you with an alternative method of writing your basic if statements. Good to know but as for which you should utilize it is really up to your own preference.

, , ,

One of the most integral parts to programming is the basic IF statement or the conditional Statement. Ruby like most if not all languages uses the if keyword to define an IF statement. However it defers from other languages as you can use the if keyword as a statement or a modifier. In addition Ruby has the unless keyword to perform the else if logic without testing for a negative result.

The basic IF ELSE statement

The IF statement in Ruby is the same as Java or C++ with the following differences like methods you don’t need to utilize parenthesis and ELSE IF has been shortened into the elsif keyword. Lets start by looking at a basic example:

if var < 10 
    puts "The variable is less than ten."
elsif var >= 10 and var < 25
    puts "The variable is less than 25 but greater or equal to ten."
else
    puts "The variable is greater then or equal to 25."
end

The IF modifier

In addition to defining IF statements ruby lets you use conditionals as a modifier. For example you can write your command and append the if modifier so that the command only executes if the test conditional is true.

puts "The variable is less than 0" IF var < 0

In the example we have written our code for outputting our string but modified it by saying only output it IF our condition is met.

The UNLESS keyword

Ruby in addition to implementing the basic IF ELSE conditional has added in the unless keyword to their language. This keyword is used to say execute the following code if and only if this condition is not met.

if var < 0
    puts "The variable is greater than 0"
else
    puts "The variable is less than 0"
end

The unless keyword is really only a convenience method for those cases your are testing for false, so instead of negating the conditional statement you can simply use unless. Like the if keyword it can also be used as a modifier.

puts "The variable is less than 0" unless var >= 0

Not sure why it was determined that the unless keyword exists in Ruby as everything it can be used for can be completed with an if statement. However from what I have seen Ruby tries to let developers do whatever they want without imposing any restrictions so i guess writing unless is easier then a negated conditional for some.

, , , , , , ,

When learning Ruby with a background in Java/C# .NET and similar high level object oriented programming languages method visibility can be a major stumbling block. To start things off all Ruby methods are by default public or accessible by any object. To limit access you have the option of modifying a methods visibility to either protected or private. Before we dive into what they mean lets look at the two ways to modify method visibility.

Modifying Method Visibility

To begin lets work with sample class that has 3 methods

class SampleClass
 
    def methodOne
    end
 
    def methodTwo
    end
 
    def methodThree
    end
 
end

By default all the methods of this class are public and accessible by anyone. To modify the method scope we need to use the private or protected modifier methods / keywords.

Named Methods

To define a single method or methods as private/protected you simply
pass a comma separated list of named methods using the syntax :methodName.

class SampleClass
 
    def methodOne
    end
 
    def methodTwo
    end
 
    def methodThree
    end
 
    private :methodTwo, :methodThree
 
end

Methods Following Keyword

If the private/protected method modifiers are used without named methods then any method defined after the keyword will have that scope. For example both methodTwo and methodThree in the below example will be protected.

class SampleClass
 
    def methodOne
    end
 
    protected
 
    def methodTwo
    end
 
    def methodThree
    end
 
end

Private Methods

Private in Ruby means the method is private to an instance of the Object. What this means is that if you mark a method as private that method still exists for classes that inherit off the object but an instance of one object can not call the private method of another instance. This varies from Java in that private methods are not available in sub classes.
Another item to remember is that private methods can only be called implicitly and not by specifying the receiver.

class SampleClass
    def methodA
    end
 
    private :methodA # defined methodA as private
 
    def callMethodA
        methodA                    # method call successfully
        self.methodA              # exception, you can not call a private method by defining the instance calling it even if it is self
        obj.methodA               # exception an instance can not access the private method of another object even if it is of the same class
    end
end

As you can see private methods in Ruby are inheritable by sub classes but can only be called in the context of the calling instance.

Protected Methods

Protected methods in Ruby share the same inheritability of Private methods. However protected methods can be accessed explicitly by other instances of the object.

class SampleClass
 
    def test( obj)
        self.var1 = obj.myTestMethod
    end
 
    protected
 
    def myTestMethod
       "hello"
    end
 
end

Pulling it all together

To make Method Visibility easier to understand one must understand that both private and protected methods are inherited by sub classes. The difference simply being that private methods can only be called in the context of an instance without defining an explicit caller of self. On the other hand protected methods are accessible from instances of the same class or inheriting sub classes.

, , , , , ,