Today’s topic deals with blocks in ruby. So the first question that you might ask is what is a block.
I will fall back to my C# experience in order to try and explain what a block is.
A block is a piece of code that you want to execute within a context of another piece of code.
I will use a string Array as an example in C# to show you what I mean. The code below creates a new instance of an array that is populated with 3 different names. I then use what is called an Action to loop through each string in the array and write the name to the console.
Here is what the code looks like.

public void DisplayNames()
{
string[] names =
new string[] {"Bob", "John", "Sam"};
Array.ForEach(names,
name => Console.WriteLine(name));
}

and here is what the Ruby code looks like:

def DisplayNames
  names = %w( Bob John Sam )
  names.each do |name|
    puts name
  end
end

The basic idea behind using blocks is that you want to perform some sort of a generic action that can be used throughout your application but you don’t want to duplicate the same code all over. In this case you can use blocks to perform this action of looping through your array and just specifying what should happen to each item.

The basic implementation of the ruby each function looks like this:

def print_values(list)
    for item in list
        yield(item)
    end
end

One interesting thing that I would like to point out is that there are different ways to pass a block to the method.

names = %w( Bob John Sam )
print_values(names) { |name| puts name }

or

names = %w( Bob John Sam )
print_values(names) do |name|
    puts name
end

What you see here is that we are creating an array of values and then we are passing that array to the print_values method which will perform the iteration logic over the array and will call the block after the print_values(names) call in order to perform what ever the logic in that block is. The yield keyword is what enables the call to the given block of code and it passes the variable that we are currently iterating over.

Advertisements

Today I wanted to talk about passing multiple arguments to functions. This can be a very useful piece of functionality if used correctly. One good example of passing multiple values to a function would be is when an application needs to validate multiple email addresses before an email is sent out to all the people in the list. This way the method signature looks very clean and all the consumer of the method has to do is simply pass in an array of all of the emails that they want to validate.

Let’s take the following code as an example of what it would look like.

def return_valid_emails(*email_list)
new_list = Array.new
email_list.each do |email|
new_list << email unless not email.valid? end new_list end return_valid_emails("valid@email.com","invalid.com") [/sourcecode]

The method above has a strange looking variable that has a “*” symbol saying that the argument is a variable array of items. Once we are inside of that method the “email_list” variable is treated as a normal Array and we can write some logic to iterate through items in the Array and perform our validation logic.

This logic consists of creating a new Array of emails and we populate that new Array by iterating through the given list of emails and validating each one. After the iteration is complete we simply return the new Array to the caller. The output of the call should be the following:

[“valid@email.com”]

If anyone has any other questions in regards to what is happening in this method don’t hesitate to ask.

Since the very first time when I started this blog I have been trying to find a better way of formatting my code. I am using Windows Live Writer to write and post my blogs and it has a lot of good plug-ins to not only format your code but many other things such as inserting pictures, videos, maps, and many many more. However I was not able to find a good plug-in to format my code and I started digging around. I am partially writing this post so I can later use this post as a reference for my self and others if they are interested.

What I have found out is that WordPress is already supporting a great code formatter tool that was written by Alex Gorbatchev called Syntaxhighlighter.
All you have to do in order to format your code is to enclose it into a sourcecode block and the wordpress engine will take care of formatting your code based on the language that you specified. Here is a simple example of what a piece of ruby code might look like:

[ sourcecode language=’ruby’]
def class BeautifulCode
  def display_beautiful_code
    puts “SyntaxHighlither rocks!!”
  end
end
[ /sourcecode]

The output after formatting will look like this.

def class BeautifulCode
  def display_beautiful_code
    puts "SyntaxHighlither rocks!!"
  end
end

Just make sure to remove the spaces that I have intentionally included in the first source code sample because WordPress would otherwise try to display the formatter version instead of the actual code that I was trying to display.

Today I am starting two new things.

1) Starting my own blog.
2) Learning ruby.

I am taking this journey for a couple of different reasons. One is that I always wanted to blog about something which I am passionate about and the second is because I started learning ruby and I am not finding as much information about it as I thought I should. I hope that by starting this blog I can document my experiences of learning ruby and hopefully share it with the rest of the ruby community.