Joining N2V

 May, 30 - 2011   5 comments   Business

Hello Dear Readers,

It’s my pleasure to announce that I have joined the marketing team of National Net Ventures — N2V , Amman branch. Therefore, I’ll relocate to Amman as well.
I’m excited to work with such a giant company helping entrepreneurs and fostering Internet industry in MENA region. Actually, that’s a part of my message in life.

I’ll give a hand in the technical efforts required by the marketing team to further expand the company’s work and message. Let’s see how things go :P

Wish me good luck people :)

Installing CoffeeScript on Ubuntu

 May, 15 - 2011   10 comments   CoffeeScript

Unfortunately the current CoffeeScript package is for an old version. Thus, some manual work is needed to get the latest version working for you on Ubuntu. Here are the steps, we need to install Git, node.js, npm and finally CoffeeScript:

Now give it a shot:

3 Factors for a Successful Startup

 Apr, 06 - 2011   1 comment   Business

Startups, like everything in life, have some key elements for success. I’m listing here what I think are the most important factors to help you moving your idea to a successful startup.

((The order here is irrelevant and all have the same equal value))


So you have the idea and you believe it’s the time to move forward. This is the proper time where you should prototype it. The purpose of prototyping is to collect enough feedback to decide whether you are going to continue and in which direction or cancel the idea altogether. Also, the prototype is helpful for marketing the idea and making relations.

The prototype should be the minimum work required to demo the idea for a group of selected people. Ideally the prototype takes 2-3 days of work. However, sometimes you need more time to demo the idea but in worst cases it shouldn’t take more than 2 weeks, otherwise you are actually coding the idea, not prototyping it, which is a totally wrong decision.
After you prepare the demo, pick a set of people including business guys and collect their feedback:

  • They do like it: This is the ideal situation. Congrats!
  • They kinda like it: This is the normal situation where you fix the workflow  and decide your next step basing on the feedback you get.
  • They don’t really like it: This case is usually referred to as “Fail Fast” or “FF”. Don’t get disappointed, make use of the feedback and rethink the whole idea. Most likely you will start from scratch with a new startup idea.

Business model

Here is the golden rule:

Launch first, then figure out the business model  is the recipe of disaster

Relaying on the “coolness” of the idea is a wrong thing. It’s all about business after all, and investors would like to understand how you are going to generate money. Actually not only that; they would like to see how confident you are when it comes to business model.

Start putting the business plan before you do any coding. Supported with estimated numbers,  the business plan will help you take the proper decision at the proper time.Adding features, updating the product, marking, expanding to new markets or even seeking fund shouldn’t be arbitrary decisions. Instead, they should be taken when needed and based on your business model.


Believe it or not, the team you pick might be the most important factor. The qualifications and the passion are the characteristics that you should look for. Even investors considers those ones, and that’s why you hear them saying: “It should be your bread and butter”. Many startups were bought or invested in because of the teams behind them apart from the business they do.

Pick your team carefully. Don’t fall in the trap of creating a bunch of geeks team. Instead, pick qualifications that you personally lack.  Having a business guy or a marketing one working with you is highly recommended when you lack those abilities of talking or marketing your work.

Don’t underestimate the role of passion when you pick your team. Passion is the work soul, it drives the work flawlessly in good times and makes it immune in bad times.  Many startups succeeded because of the team’s passion despite the bad times they faced, and vise versa, some of them had talents but lacked the passion and finally they failed miserably.

Feel free to add your comments on those factors and what you think might also be a missing one.

Google App Engine, JRuby, Sinatra and some fun!

 Mar, 06 - 2011   24 comments   GAEJRubyRubySinatra

Yesterday I was experimenting with Google App Engine for a little project that I was working on. I literally started from ground zero and could do my thing after a long night. I’m blogging about it to share you the idea and save you some time googling solutions. So, here is the thing in brief: I wanted to parse some feed on periodical basis and send an email with new entries.

Looks like a 10 minutes with Nokogiri and cron jobs. Actually that’s true except of the fact that I need to pay for a VPS so that I can run the script with various gems (since I needed to do some work on the feeds before sending, but that’s for another topic) and for using cron jobs. Thus, I decided to try something new this time and I went with GAE since it has memecached that I can use as an LRU cache, also it has cronjobs and finally it has a mail system. I’m using JRuby and Sinatra for this project.

Here are the steps:

Install JRuby, I’m using RVM on my machine:

Install needed gems, those versions are the ones which worked for me:

Create a simple app:

Now let’s create the following files (Please note that the following code can be further enhanced):


(fill the sender/receiver emails and the feed URL)



(You can set the period here, I’m using 15 minutes intervals)

Now, create an application-id at Then go to Administration >> Permissions and make sure the sender/receiver emails play some role in the app. Personally, I granted them the developer role.

Now, go back to the source and modify the application-id in WEB-INF/app.yaml

We should be ready now, start development server, watch the console and make sure no exceptions are there:

If everything is OK, go to http://localhost:8080/notfiy and you should see “Done”.

Let’s go live now:

(the first time you execute this, you will prompted to submit the GAE email/pass combination)

It should now be running at, and in few minutes you should be receiving the first email. If not, go to app engine page then to Main >> Logs and check what’s the problem.

I like this stack cause it’s Zero cent cost, Zero deployment time, flexible, and it gives me exactly the freedom I want in terms of needed gems. Give it a shot, you won’t regret it!

Test or Regret!

 Jan, 31 - 2011   no comments   Test

Yes, for god sake test! Whoever you are, a web/desktop/mobile developer please add automated tests to your work. If you don’t then your works is questionable.
Why? That’s what I’m going to answer in the next few lines.


Were you in the case where you or a new developer joined a team? Were you in the case where you got to work on a legacy code? Were you in the case where you forgot what your own code was doing?
All the above scenarios are normal during your lifetime as a developer or a team lead. All of them have a common shared thing: What is this code doing? and where to start?
Adding automated tests to the project code base, where a test case refers to a real world scenario that the code has to deal with, is the ideal answer for the questions above.
When you add a test scenario, then technically you are adding a new spec on how the code should behave in that scenario. When you add automated tests for some module, then referring to these tests is the first thing you can do to understand how/what this module is doing and behaving in different cases.
The bottom line is that automated tests are your project specs.

Clean Code

A test usually checks the output/behavior of some method. Once you start testing you will find yourself in need to restructure your code in a way that you can test it. Technically, you will make sure the method is doing one thing and one thing only. One thing that can be tested like this: given some input x, the method should have some output y. Following this pattern(which technically you will be forced to when doing automated testing) will lead to a clean code, a code that doesn’t mix responsibilities and thus become harder to be read, updated and maintained.

Code Quality

New features will come, you have to update/refactor the code and then go and do some human tests to make sure everything you developed ever will work. This is called Regression Testing, test to make sure you didn’t break old code. Doing regression testing yourself is a natural thing and it will continue to be like that till your code base starts to evolve and evolve till you reach a level where doing a small fix in the code will make you scared to death before releasing since you have to do tens of human tests to make sure you didn’t break anything. Of course this will get worse if you are modifying others code. You simply(and really simply) can overcome this regression testing routine if you have a test suite for your code base that you can fire after whatever change you do to check what code is broken and what’s needed to be fixed. This will produce a robust code. Not only that, actually it will increase the code quality since whatever bug you have at some phase of the project, will be fixed and the fix will have an associated test scenario that will be added to the test suite. Next time when you update the code, the test suite will test that bug scenario to make sure you didn’t reproduce it again.

Agile Development

Most of the time you will have new requested features, or new discovered bugs. You have to add/fix whatever needed. Doing the changes and then doing human testing will consume your time and thus will slow down the project development and progress, and so will prevent it from iterating quickly. Having a test suite will save the time, and will complete the chain of Design, Test and Refactor methodology that Agile development poses. Actually some of you might think that adding automated tests will slow down the progress of development, which is wrong, very wrong. As a start it might slow it down, but after that it will save your time specially once your project starts to iterate with new features or bug fixing.


Test or you’ll regret! and if you want to do it, then do it right. I advice you to check Behavior Driven Development(BDD), a methodology of development that’s based on testing the behavior of your code.

2011 and I’m back!

 Jan, 31 - 2011   2 comments   PythonRuby


It has been long time since I opened this page to write something. Actually 2010 was a very busy year. I left ArabCrunch team to join Inquiro, a cool startup focusing on SEO/SEM optimization, where my work completely took a different path and a whole shift. I became a team lead for a cool project using Python/Django stuff. Really enjoyed working there and loved the environment, I even had to cross half the planet(20 hours in air) to meet the managers and get acquainted to a whole new culture in life.

However, few weeks ago, I started to realize that I don’t belong to where I was working, since I always had the dream to do my own thing, always lacked the motivation. Yes, that was always the case, no motivation. Up till the cool ppl behind YallaStartup did a wonderful weekend startup event that I participated in. After that event things changed quickly and I decided to leave my job for my own startup. I’m spending whole time now work on my thing and I’m very glad to be so. In later posts I’ll describe what I’m doing in better details.

Now, I want to make use of this chance to express who much I missed Ruby and the whole community. Yes I really did. Now, I’m back and I’ll try to frequently update this blog with new life experience.

Just before I publish this post, for the little of you who are wondering whether Python is cool or not, indeed it’s very cool and so much similar to Ruby, but it lacks the great community that Ruby has.

Yes, now I can publish! C ya!!

StackOverflow cool Ruby questions 4

 Mar, 16 - 2010   8 comments   RubyStackoverflow

Welcome to the fourth post of this series. Just before proceeding to the questions, I would like to mention the great Metaprogramming Ruby: Program Like the Ruby Pros book by Paolo Perrotta, a very good book that explains the metaprogramming aspects of the Ruby language.
Now let’s get going!

Scope gates

Taken from the above mentioned book:

There are exactly three places where a program leaves the previous scope behind and opens a new one:
• Class definitions • Module definitions • Methods
Scope changes whenever the program enters (or exits) a class or module definition or a method. These three borders are marked by the keywords class, module, and def, respectively. Each of these keywords acts like a Scope Gate.

The question title is: Closure doesn’t work

The question text is:
If block is a closure, why this code does not work? And how to make it work?

The answer is:
Blocks are closures and arg is indeed available inside the block. It’s just not available inside the foo method because def starts a new scope. If you replace def with define_method, which takes a block, you’ll see the result you want:

Almost everything in Ruby is an object

The question title is: Examples of ‘Things’ that are not Objects in Ruby

The question text is:
“Everything is an object” was one of the first things I learned about Ruby, but in Peter Cooper’s Beginning Ruby: From Novice to Professional book, it is mentioned that “almost everything in Ruby is an object”.

Can you give me some examples of things that are not objects in Ruby?

The answer is:
he most obvious one that jumps into my head would be blocks. Blocks can be easily reified to a Proc object, either by using the &block parameter form in a parameter list or by using lambda, proc, or (in Ruby 1.9) the “stabby lambda” syntax. But on its own, they aren’t objects.

Another example are built in operators: while methods are objects, some operators are not implemented as methods (and, or &&, ||), so those operators aren’t objects.

Hash keys

The idea here is that whenever you want to define your own keys types for Ruby hashes, then you need to define 2 methods #eq? and #hash for those types.

The question title is: How to make object instance a hash key in Ruby?

The question text is:
I have a class Foo with a few member variables. When all values in two instances of the class are equal I want the objects to be ‘equal’. I’d then like these objects to be keys in my hash. When I currently try this, the hash treats each instance as unequal.

f1 and f2 should be equal at this point.

should print 8

The answer is:

Hash uses key.eql? to test keys for equality. If you need to use instances of your own classes as keys in a Hash, it is recommended that you define both the eql? and hash methods. The hash method must have the property that a.eql?(b) implies a.hash == b.hash.

The eql? method is easy to implement: return true if all member variables are the same. For the hash method, use [@data1, @data2].hash


The question title is: Ruby – Exit Message

The question text is:
Is there a one line function call that quits the program and displays a message? I know in Perl its as simple as this:

Essentially I’m just tired of typing this:

The answer is:
The ‘abort’ function does this. For example:

StackOverflow cool Ruby questions 3

 Jan, 29 - 2010   6 comments   RubyStackoverflow

Welcome to the third post of this series. Just before diving into the new questions’ set, I want to mention a little script that I wrote to notify the user when a new question is posted on Stackoverflow, it works on Mac and uses growl.
Now let’s proceed to questions:

Relationship between the metaclass of base and derived classes

The question title is: What is the relationship between the metaclass of Base and Derived class in Ruby?

The question text is:

In Ruby, we could use super within singleton method to call the corresponding super class’s singleton method, like the following code shows.

However, I don’t seem quite get how that call to super within Derived.class_method could reach Base.class_method. I’d assume that class_method is defined on their metaclass, does that mean their metaclass has parent/child relationship? (I can’t quite confirm that by experiments)

I’m asking this question because I remembered seeing somewhere there’s some kind of relationship between base and derived class’ metaclass (but I can’t find it any more). In addition to know how actually super works, I’d also like to confirm whether the two metaclasses are totally separate or not.

The answer is:
There are four class objects in play here:


  • <...> is the class of each object.
  • The name of the class is on the second line.
  • If the name starts with #, it’s the eigenclass (aka singleton class).
  • super points to a class’s superclass
  • class points to the class’s class.

When you call Derived.class_method, Ruby follows the “right one and then up” rule: First go to the object’s class, then follow the superclass chain up, stopping when the method is found:

  • The receiver of the “class_method” call is Derived. So follow the chain right to Derived’s class object, which is its eigenclass (#Derived).
  • #Derived does not define the method, so Ruby follows the chain up the chain to #Derived’s superclass, which is #Base.
  • The method is found there, so Ruby dispatches the message to #Base.class_method

You don’t think I knew all this stuff off the top of my head, did you? Here’s where my brain got all this meta juju: Metaprogramming Ruby.

Part 2. How to make an “eigenclass” (aka “singleton class”) come out of hiding

This method will return the eigenclass of any object. Now, what about classes? Those are objects, too.

Note: Above is from Ruby1.9. When run under Ruby 1.8, you get a surprise:

Idiomatic object creation

The question title is: Idiomatic object creation in ruby

The question text is:

In ruby, I often find myself writing the following:

or even

I’m always keen to minimize boilerplate as much as possible – so is there a more idiomatic way of creating objects in ruby?

The answer is:

Struct objects are classes which do almost what you want. The only difference is, the initialize method has nil as default value for all it’s arguments. You use it like this


Struct has one big drawback. You can not inherit from another class.

Block vs brackets

The question title is: Using do block vs brackets {}

The question text is:

New to ruby, put on your newbie gloves.

Is there any difference (obscure or practical) between the following two snippets?

I realize the bracket syntax would allow you to place the block on one line

but outside of that are there any compelling reasons to use one syntax over the other?

The answer is:

Ruby cookbook says bracket syntax has higher precedence order than do..end
Keep in mind that the bracket syntax has a higher precedence than the do..end syntax. Consider the following two snippets of code:

Second example only works when parentheses is used, 1.upto(3) { |x| puts x }

String and whitespace

The question title is: See if a ruby string has whitespace in it

The question text is:

I want to see if a string has any white space in it. What’s the most effective way of doing this in ruby?


The answer is:

If by “white space” you mean in the Regular Expression sense, which is any of space character, tab, newline, carriage return or (I think) form-feed, then any of the answers provided will work:

Index of the largest value in an array

The question title is: In Ruby, what is the cleanest way of obtaining the index of the largest value in an array?

The question text is:

If a is the array, I want a.index(a.max), but something more Ruby-like. It should be obvious, but I’m having trouble finding the answer at so and elsewhere. Obviously, I am new to Ruby.

The answer is:

For Ruby 1.8.7 or above:

It does one iteration. Not entirely the most semantic thing ever, but if you find yourself doing this a lot, I would wrap it in an index_of_max method anyway.

each_with_index without a block returns an enumerator that gives the item and its index. We then send max to this enumerator, which does the standard max algorithm on item-index pairs. Array.<=> is implemented so that the first item determines the ordering (unless there’s a tie, in which case the second is compared, and so on), so this works basically the same as doing max on an array of the values themselves. Then to get the index, we ask for the second item of the result (since we got a series of [value, index] pairs from each_with_index)

StackOverflow cool Ruby questions 2

 Oct, 17 - 2009   8 comments   RubyStackoverflow

Welcome in this second post of this series. Just before I list the questions of this one, I want to mention 2 things:

  • You can follow StackOverflow tagged Ruby questions on twitter using the user: sof_ruby
  • Some ppl feel shy to ask or even to answer, my (little) experience in life taught me that If you don’t ask, you don’t learn. If you don’t participate, you don’t learn. On the other side that’s the benefit of pair programming, ain’t it?

Now let’s proceed to questions:

Hash Autovivification

Hash Autovivication in simple words is the ability to do things like:

The cool idea here is that all intermediate-level hashs will be created automatically.
We can’t do that directly in Ruby, a statement like the previous one will issue an error : NoMethodError: undefined method `[]' for nil:NilClass

The question title is: ruby hash autovivification (facets)

The question text is:
Here is a clever trick to enable hash autovivification in ruby (taken from facets):

Although it works (of course), I find it really frustrating that I can’t figure out how this two liner does what it does.

The answer is:
The standard new method for Hash accepts a block. This block is called in the event of trying to access a key in the Hash which does not exist. The block is passed the Hash itself and the key that was requested (the two parameters) and should return the value that should be returned for the requested key.

You will notice that the leet lambda does 2 things. It returns a new Hash with leet itself as the block for handling defaults. This is the behaviour which allows autonew to work for Hashes of arbitrary depth. It also assigns this new Hash to hsh[key] so that next time you request the same key you will get the existing Hash rather than a new one being created.


Class instance variables

This answer of this one is easy, but the idea of Class instance variables is what matters.

The question title is: Total newbie: Instance variables in ruby?

The question text is:
Pardon the total newbiew question but why is @game_score always nil?

The answer is:
Because you don’t have

The assignment in the class definition is not doing what you think it is doing, and when hit gets invoked it can’t add to nil.
If you now ask what happened to @game_score?, well, always remember Class is an object and Object is a class.
It’s way cool the way Ruby classes have this Zen-like “real” existence. Ruby doesn’t precisely have named classes, rather, class names are references to objects of class Class. By assigning to @game_score outside of an instance method you created a class instance variable, an attribute of the class object Bowling, which is an instance of class Class. These objects are not, in general, very useful. (See Chapter 1, The Ruby Way, Hal Fulton.)

You can reach the @game_score class instance variable by doing this:

(A question for you: What is the difference between class variables and class instance variables?)

Creating data structures in Ruby

I have committed a mistake myself in answering this question :P, however remember: If you don’t try, you don’t learn.

The question title is: Can the array be reinvented in Ruby?

The question text is:
This is just a hypothetical question, if you wouldn’t have the Array and the Hash class, would there be any way of implementing an Array class in pure Ruby? How?

The answer is:
Yes we can:

This works by creating instance variables @a0, @a1, etc. on the object to represent array indices 0, 1, etc. It has constant time length and index operations. The rest of the operations (remove, etc.) are a bit more effort to implement, but it’s absolutely possible.

Note that the constant time property for the index operation depends on the underlying Ruby runtime using an appropriate data structure for instance variables.


The question title is: Update attributes unless blank?

The question text is:
I have an existing Project record, and I’m importing a CSV file to update the associated Project attributes. However, often the CSV will contain blank fields and I don’t want to overright exisiting attributes if the related CSV field is blank.

Something like this:

The answer is:

Ruby ‘private’ behavior

The key point here to remember is that private, protected and pulbic are just other methods defined in Ruby Module class.

The question title is: Are there good reasons for ‘private’ to work the way it does in Ruby?

The question text is:
It took me a while to understand how private methods work in Ruby, and it really strikes me as being very awkward. Does anyone know if there are good reasons for private methods to be handled the way they are? Is it just historic reasons? Or implementation reasons? Or are there good solid logical reasons (ie. semantic)?

For example:

  • Ruby’s behaviour on lines (1), (2) and (5) seems reasonable.
  • The fact that (6) is ok is a bit strange, especially coming from Java and C++. Any good reason for this?
  • I really do not understand why (3) fails ! An explanation, anyone?
  • The problem on line (4) looks like an ambiguity in the grammar, which has nothing to do with ‘private’.
  • Any ideas?

The answer is:

You might find it helpful to read ruby’s definition of public, private and protected (Skip to Access Control)

Ruby’s private is analogous to Java’s protected. There is no Ruby equivalent of Java’s private. But there are ways to fake it.

Private is defined as methods/variables that can only be called implicitly. This is why statements 2 and 3 fail. In other words, private limits methods/variables to the context of a class or subclass in which they are defined. Inheritance passes private methods to the subclasses and can therefore be accessed with an implicit self. (Explaining why statement 6 works.)

I think you’re looking for something closer to protected. Which behaves similarly to Java accessors that are not given a visibility (eg: public, private, protected) By changing the private in Spy to protected all 6 of your statements work. Protected methods can be called by any instance of the defining class or their subclasses. Either explicitly or implicitly called on self are valid statements for protected methods so long as the caller is either the class of the object responding to the call, or inherits from it.

As for statement 4. You are correct in assuming this is to avoid ambiguity. It’s more a safeguard to the potential harm of ruby’s dynamic nature. It ensures that you cannot override accessors by opening up the class again later. A situation that can arise, for example by eval’ing tainted code.

I can only speculate on he design decisions that led to these behaviours. For most of it I feel it comes down to the dynamic nature of the language.

P.S. If you really want to give things the java definition of private. Only available to the class in which it’s defined, not even subclasses. You could add an self.inherited method to your classes to remove references to the methods you want to limit access to.

Making the weight attribute inaccessible from subclasses:

It may make more sense to replace the undef_method call to something like this:

Which provides a much more helpful error and the same functionality.

The send is necessary to get around calling private methods for other classes. Only used to prove that things are actually working.

Which in hindsight, makes private and protected useless. If you’re really serious about protecting your methods you will have to override send to block them. You could also make send private.

It ends up being one of those “Damned if you do, damned if you don’t” situations. There are legitimate uses of calling send from outside an object. And overriding send requires some tricky code to account for the variable number of arguments that can be sent to any method.

That’s an exercise for another time.

Suggestions/comments regarding the content of this series are welcome! Have your say!

StackOverflow cool Ruby questions

 Sep, 29 - 2009   10 comments   RubyStackoverflow

I have participated heavily during the last 2 weeks in answering Ruby tagged questions on stackoverflow. That took place mainly after Ryan Bates tweet wishing to see more Ruby developers on stackoverflow. Since then I have enjoyed reading various kinds of questions that range in level from basic to professional ones and which cover various stuff like normal questions, tricks, meta programming, best practices and language specific features.

So, I’m announcing in this post an endless series called “Stackoverflow cool Ruby questions” which will target cool Ruby questions on stackoverflow. I strongly recommend that you visit Stackoverflow on daily basis and try to participate if you have the time, but if you don’t, then I hope that you will enjoy this educational series.

There are currently more than 4,640 tagged Ruby questions, I’ll try to mix old + recent questions. I won’t cover basic questions here unless the question gets high votes. The covered questions will be related to new, tricky and controversial topics.

Please don’t hesitate to give any notes regarding the idea and the way the questions are picked and presented.

Let’s start this series, with 3 questions for this post:

‘Instance_eval’ instead of ‘yield(self)’

The question title is: Instance Eval Within Block

The question text is:

Now, how do I change this

Into this?

The answer is:

The trick here is to use instance_eval which evaluates the passed block in the context of the current object called on.

Determining whether a variable is any one of a list of values

The question title is: Shortest/most idiomatic way of determining whether a variable is any one of a list of values

The question text is:

This seems a ridiculously simple question to be asking, but what’s the shortest/most idiomatic way of rewriting this in Ruby?

I’ve previously seen this solution:

but this isn’t always functionally equivalent – I believe Array#include? actually looks to see if the variable object is contained in the list; it doesn’t take into account that the object may implement its own equality test with def ==(other).

Take, for example, Rails’ Mime::Type implementation: request.format == :html may return true, but [:html].include?(request.format) will return false, as request.format is an instance of Mime::Type, not a symbol.

The answer:
Actually, #include? does use ==. The problem arises from the fact that if you do [:a].include? foo, it checks :a == foo, not foo == :a. That is, it uses the == method defined on the objects in the Array, not the variable. Therefore you can use it so long as you make sure the objects in the array have a proper == method.

In cases where that won’t work, you can simplify your statement by removing the select statement and passing the block directly to any:

Using ‘instance_eval’ instead of ‘send’

The question title is: How to evaluate multiple methods per send command?

The question text is:

Let’s say I have an XML::Element…I want to do something like:

The answer is:

In your case it’s better to use instance_eval

And for your code: