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.

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")

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.

Coming from a .NET background I was always used to using properties in my classes in order to either expose the values of my variables to the consumer of my class or to perform some sort of caching so I don’t have to have the same logic duplicated throughout my class.
An example of that code might look like this:
public class TestClass
{
string _firstName;
public string FirstName
{
get
{
if(string.IsNullOrEmpty(_firstName))
{
_firstName = UserDAL.GetFirstName();
}
return _firstName;
}
}
}

After starting to learn Ruby On Rails I have learned that there is a very simple way to do the same thing with much less code.

def class TestClass
 def first_name
  @firstname ||= User.first.FirstName
 end
end

One thing to watch out for is that the ruby code above checks to see if the value of the variable is not null and it will return the value that is set. This means that if you wanted to return a result based on a constantly changing criteria then this is not the correct way of performing caching because the statement that occurs after the “||=” only gets evaluated once unless the result of that statement returns nil.

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.

Last week I was reading a chapter in a RailsSpaces book and because the book was written in 2007 the code was a bit outdated. The issue that I was running into was the author was using the sprintf() function to format a string that is part of the ActiveRecord error messages. This is a problem because the ActiveRecord uses error messages such as :

“is too short (minimum is {{count}} characters)”

where the word in the double curly braces is the placeholder for the value that the developer must replace. I first thought that I simply was not using the sprintf() function correctly until I discovered that the sprintf() was the wrong method to use in the first place. What should be used is a new class that was introduced to Rails in version 2 called I18n which is a new way of localizing the text in rails applications. The correct way of formatting those kinds of messages in Rails now is:

I18n.translate("activerecord.errors.messages.too_short",
				:count=> some_value)

Today I had a great opportunity to attend one of the local Ruby User Groups in Cleveland OH. It was a very interesting experience where a group of people were trying to solve a problem. The problem that they were trying to solve is to implement a bowling calculation class using BDD and RSpec. The group consisted of 6 people but only 2 people were working on a problem at any point and time where one person would sit down and write the test and hand the keyboard and mouse to the other person and have them write the minimal amount of code to make the test pass. After 10 minutes of going back and forward the person who was writing the code to pass the tests walked away from the computer and the person writing the tests ended up in the driver seat to write the code and a new person would come in to write the tests.
I was amazed at how easy it was to write the test and then have to write the code to satisfy the test.
I have made my first attempt at writing my very first test and below you can see the results of a very interesting factory class and a RSpec test that I ended up writing.

In order to run the code that I have below you will have to make sure that you have RubyGems and RSpec gem installed.

   1: # factory_spec.rb

   2: require 'rubygems'

   3: gem 'rspec'

   4: require 'factory'

   5:  

   6: describe "should test factory's output" do

   7:     before(:each) do

   8:         @factory = Factory.new

   9:         @factory.make_cars(0)

  10:     end

  11:     

  12:     it "should return 0 when 0 is passed as an argument" do

  13:         @factory.daily_output.should == 0

  14:     end

  15: end

Here is the sample class that I wrote in order to satisfy the test that is written above:

   1: #factory.rb

   2: class Factory

   3:     def make_cars(carcount)

   4:         @blah = carcount

   5:     end

   6:     def daily_output

   7:         @blah

   8:     end

   9: end

Then to run the code below you will have to execute the following command:

   1: spec -f s --c factory_spec.rb

And the output of the above test looks like this:

   1: ilya@RubyDev:~/projects/ruby/testing$ spec -f s --c factory_spec.rb

   2:  

   3: should test factory's output

   4: - should return 0 when 0 is passed as an argument

   5:  

   6: Finished in 0.003434 seconds

   7:  

   8: 1 example, 0 failures


After having to get my hands dirty writing this test things all of a sudden started making sense. Having to write tests before writing the code seems like a lot of work for a beginner TDD or BDD coder but after some time the benefits of having to think about the requirement and then coding makes you think about the problem at hand and then appropriately coding a solution.

If you have any comments please do not hesitate to respond and I can try my best to answer any questions.

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.

Follow

Get every new post delivered to your Inbox.