StackOverflow cool Ruby questions 4

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

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

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

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:

Bringing web applications to your Desktop with Prism

I have almost finished working on a web app that will be used inside intranets by students willing to do their English language exams interactively. I have reached the point where I want the app to have as much as possible the look of a desktop one. So I started thinking that may be with the help of Javascript I might be able to remove the browser toolbar; not a bad idea so far. Also I wanted to disable both back and refresh buttons because the exam is timed and the student will have a time counter for each section. However after I ran through this thread and found a strong resistance towards such ideas, I decided to go with other solution. Simply I chose to remove the toolbar and use keystroke events to determine which ones are related to navigation, just like ‘f5’ and ‘backspace’. So far so good, but after few minutes of work on this approach, I had few thoughts at mind: “Why am I doing so? Do I really need a browser to do this? shouldn’t be there any software that can render HTML markup and can have a customized interface?”
I start searching for such a software and found Prism, which is a cool product by Mozilla that helps you turning a web app into a desktop like one. Taken from the product why page:

Instead of running all your web apps in the browser, Prism lets you run them in their own window just like normal applications. A single faulty app or web page can no longer take down everything you are working on.

Prism is so easy to be used, it takes 1 minute approximately to turn your web app into a desktop one and you will gain many Desktop integration things like:

  • Access web apps from system taskbar or dock
  • Tray icon and dock menus
  • Associate applications with browser links
  • Minimize to tray
  • System tray icon and dock badges

Prism can be used as a stand alone soft, or just another Firefox addon(this one didn’t play well with me). Give it a shoot, you won’t regret it!

Observer and Singleton design patterns in Ruby

This is my first article in, it was published in issue 3, so basically I’m just republishing it here again.

Observer and singleton are two common design patterns that a programmer should be familiar with, however what made me write about them, is that both are there out of the box for you to use in ruby.
So let’s have a look at both and see how ruby help you use them directly:

Observer Design Pattern

According to Wikipedia:

The observer pattern (sometimes known as publish/subscribe) is a software design pattern in which an object, called the subject, maintains a list of its dependents, called observers, and notifies them automatically of any state changes, usually by calling one of their methods. It is mainly used to implement distributed event handling systems.

So how does ruby help you implementing this design pattern? Well, the answer is by mixing the observable module into your subject (observed object).
Let’s take an example, let’s suppose we have a banking mechanism that notifies the user by several ways upon withdrawal operations that leaves the account with balance less or equal to $0.5.
If we look deeply at this problem, we can qualify it as a good candidate for observer design pattern, where the bank account is our subject and the notification system as the observer.
Here is a code snippet for this problem and it’s solution:

So to user ruby observer lib we have to implement four things:
1- Require the ‘observer’ lib and include it inside the subject (observed) class.
2- Declare the object to be ‘changed’ and then notify the observers when needed – just like we did in ‘withdraw’ method.
3- Declare all needed observers objects that will observe the subject.
4- Each observer must implement an ‘update’ method that will be called by the subject.

Observers in Rails

You can find observers in rails when using ActiveRecord, it’s a way to take out all ActiveRecord callbacks out of the model, for example a one would do this:

A neater solution is to use Observers:

You can generate the previous observer using the following command:

You still can have observers that map to models that don’t match with the observer name using the ‘observe’ class method, you also can observe multiple models using the same method:

Finally don’t forget to add the following line inside config/environment.rb to define observers:

Singleton Design Pattern

According to Wikipedia:

In software engineering, the singleton pattern is a design pattern that is used to restrict instantiation of a class to one object. (This concept is also sometimes generalized to restrict the instance to a specific number of objects – for example, we can restrict the number of instances to five objects.) This is useful when exactly one object is needed to coordinate actions across the system.

The singleton design pattern is used to have one instance of some class, typically there are many places where you might want to do so, just like having one database connection, one LDAP connection, one logger instance or even one configuration object for your application.
In ruby you can use the singleton module to have the job done for you, let’s take ‘application configuration’ as an example and check how we can use ruby to do the job:

So what does ruby do when you include the singleton method inside your class?
1- It makes the ‘new’ method private and so you can’t use it.
2- It adds a class method called instance that instantiates only one instance of the class.
So to use ruby singleton module you need two things:
1- Require the lib ‘singleton’ then include it inside the desired
2- Use the ‘instance’ method to get the instance you need.

Ruby 1.9 Encoding Fun

Ruby 1.9 has a great support for encoding, this post covers that for a big deal, however with this support out of the box, things like this becomes easier, just note the source code is not limited to few types of encoding just like Ruby 1.8.

Please note that previous example could work also with Ruby 1.8 using the flag -Ku, I just wanted to explain the idea of using different types of encoding in Ruby 1.9.

So all you need to do is to set whatever encoding you want for your source code at the very beginning of the file:

Many other things can be done, just give yourself a moment and think what you can do!

Scala is my next choice

I have done Pascal, C, C++, Java, PHP, Ruby, Groovy and recently Scala, which I found it to be a unique language compared to anything else I have ever worked with. My journey with this language started after the Twitter’s Ruby vs Scala debate. Now and after few months of work with this language I really want to share you two ideas that are no secrets anymore:

  • Scala Does Rock.
  • I do believe this language should be taught in CS colleges and institutes.

I’m going to justify my opinion during this article, just before doing so I have few notes I feel like I have to address:

  • This article is not to compare languages, it’s to address why you should learn Scala.
  • Scala has 2 implementations right now, one that runs on the JVM, and one that runs on the CLR. However the JVM one is more mature, and I believe it’s better to stick to the advice of David Pollack(Lift framework creator) to use F# if you want to work with .Net framework. However I will stick to JVM implementation in this article.
  • I’m a Rubiest, and I still like Ruby cause it’s the best dynamic language ever, but I like Scala also because it has some features that are so powerful for other work domains.

Now, let’s dive into the some reasons that’s makes Scala my next language of choice:

A hyper language

Scala is a hyper language that enables you to code in imperative and functional paradigms, so you can code with the normal imperative style just like we do in C, Java, PHP and many other languages, or you can code in a functional style like we do in Lisp for example, or you can mix both, just like we do in Ruby or Groovy.

However, one distinct to Ruby and Groovy when talking about the functional paradigm, is that Scala almost supports all known features of functional languages, like Pattern matching, Lazy initialization, Partial Functions, Immutability, etc…

That’s said, it’s important to address the fact that the power of Scala comes from it’s support for the functional paradigm, which makes the language a high-level one. A high-level language makes you focus on ‘what’ to do rather than ‘how’ to do.

Look at this Java example:

If you focus on the previous example, you will notice that the ‘what’ part of what I want to do (Filtering odd values) comes on the 4th line, and the other lines are just the ‘how’ part of it(result var initialization and a loop), thus if I want to write another filter for even numbers, It will take me another 5 lines to do the same, while in a high-level languages like Scala, you will need to express the ‘what’ part only:

Notice how the previous code snippet is more readable and more concise than the Java equivalent.


Scala is an efficient language, actually due to the latest benchmarks Scala is almost as fast as Java. The JVM implementation of Scala compiles down to bytecode, but during so, the code passes through optimization phaze. An optimization example is the tail recursion optimization, to help you stick to the functional paradigm without sacrificing the performance. Another example is the optimization done to convert Scala value type objects to Java primitive types.


The name of Scala language comes form the word ‘Scalable’, meaning that this language grows with the demand of its users. So basically you can add new type and control structures. For example I want to add a simple ‘loop’ control structure:

A more comprehensive example is the Actor lib, which is added as an extension to the language, we will talk about it later on.

However what makes Scala Scalable is two related things: being pure object oriented and being functional.

Object Oriented

  • Everything in Scala is an object(except for the objects’ methods), so there is no need to differentiate between primitive or reference types, this is called: Uniform Object Model. But as I mentioned earlier during the optimization process, value type objects are converted to Java primitive types, so don’t be worried about the performance.
    There are also singleton objects to group class methods inside them.
  • All operations are method calls, + - * ! / all are methods, so there no need for operator overloading.
  • A great fine-grained access control, where you can control access for certain methods for certain packages also.
  • Scala has traits, similar to mixins in Ruby, which are like interfaces in Java but have some of their methods implemented, thus you can have rich wrappers and interfaces out of the box.


A functional language has many characteristics, however what we care for in our Scalability context is 2 facts:

Functions are first-class values

Which means that you can pass them as values and return them as values as well. This leads to concise readable code just like the filtering examples mentioned above.

Pure functions

Scala encourages pure functions that have no side effects, meaning: when you have the same input, you will always have the same output. This will result in safer and easier to test code.
But how does Scala encourages pure functions? By immutability: Favoring fixed references(like final in java or constants in other languages) and having immutable data structures that once created can’t be modified.

Immutability is the safe guard to have pure functions, but it’s not the only way. You still can write safe code without immutability. That’s why Scala doesn’t force immutability but it encourages it. Eventually you will find that many data structures in Scala have 2 implementations, one is mutable and the other is immutable, immutable data structures are imported by default.

Some concerns regarding performance might arise when talking about immutability, and while these concerns are valid in this context, it turned out that things are somehow reversed when it comes to Scala. Immutable data structures tend to be more efficient than mutable ones. One reason for that is the existence of a robust garbage collector like the one of JVM. You can find more information about the efficiency of immutable data structures in Scala in this blog post.

Better concurrency model

When it comes to threading, Scala supports the traditional shared data model. However and after long experiments with this model, many people found it to be so hard to to implement and test concurrent code written using this model. You will always have to consider deadlocks and race conditions. Thus Scala suggests another concurrency model called Actors, where an actor sends and receives asynchronous messages in it’s inbox instead of sharing data. This is called: shared nothing model. Once you stop thinking about shared data, you relief yourself from the headache of thinking of code synchronization and deadlocks problems.

Together the immutability nature of the sent messages and the serial processing of messages in the actor, leads to easier concurrency support.
There are 2 articles(1,2) on the IBM developerWorks website that cover Scala concurrency deeply. Please refer back to them to have a better idea about this topic.

Before I move to the next point I need to mention the fact that some people consider the use of Actors as an evolutionary progress in programming languages. As Java came and relieved programmers from the headache of pointers and memory management, Scala came to relief programmers from thinking all the time of code synchronization and the problems raised by shared data model.

Statically typed

When i wanted to cover this point, I found myself trying to weigh both the pros and cons of a statically typed language. Actually there is an endless debate regarding this topic but I tried to sum things up to two points that I found most people talking about:

Code written in statically typed languages is more robust

It’s true that with the existence of TDD most of the talk about dynamically typed systems and robust code starts to lose its value, but one fact still exists: in dynamically typed languages you write more tests to check types, while in statically typed ones, you leave things out for the compiler. Also some people argue that with a statically typed language you have a better self documenting code.

Code written in statically typed languages is so strict and verbose

Fans(just like me) of dynamically typed languages argue that they can produce more dynamic code structures through duck typing. Also they complain about the verbosity introduced with statically typed languages.

You can read more about static versus dynamic typing here.

Scala as a statically typed language will gain the first point, but how about the second one?
Scala has a flexible type system, and may be the best of it’s type. So in many cases this system will be able to infer the type in case you didn’t specify it.
For example you can do this:

But you can do this also:

Well, that’s cool as it solves the verbosity problem somehow. But what about things like duck typing?
Again: Scala’s type system has some flexibility that enables you to do things like:


pre lang=”Scala”>
def eat[T <: Animal](a: T) // whatever

Where we define the Type T to be a sub type of Animal. It can be more flexible even:


pre lang=”Scala”>
def eat[T <: {def eat(): Unit}](a: T) // whatever

Where we define the type T to be a type that has the method eat.
Actually Scala’s type system is so rich, you can find more about that here.

Pattern matching

I have to admit that I hesitated a lot to write about this feature, actually I didn’t want to cover functional features of Scala, but after I read this specific post regarding switch use with objects, I thought it’s good to talk about this feature.
So basically and taken from this post :

So what does pattern matching do? It lets you match a value against several cases, sort of like a switch statement in Java. But instead of just matching numbers, which is what switch statements do, you match what are essentially the creation forms of objects.

And the following example:

In the first case, the pattern Name(first, last) is nested inside the pattern Address(…). The last value, which was passed to the Name constructor, is “extracted” and therefore usable in the expression to the right of the arrow.


The purpose of pattern matching

So why do you need pattern matching? We all have complicated data. If we adhere to a strict object-oriented style, then we don’t want to look inside these trees of data. Instead, we want to call methods, and let the methods do the right thing. If we have the ability to do that, we don’t need pattern matching so much, because the methods do what we need. But there are many situations where the objects don’t have the methods we need, and we can’t (or don’t want to) add new methods to the objects.

So, Pattern matching is considered a valid way of extensibility, and it offers a great solution to this problem apart from the verbosity that comes with Visitor design pattern.

Anyway, it’s highly recommended that you read the “Two directions of extensibility” in the previous mentioned article.

Easy DSLs

Scala is very good for coding DSLs. Actually Scala is suitable for both Internal and external DSLs. You can find in this article a little comparison of features between Ruby and Scala for writing internal DSLs. Check this cool post on internal DSLs using Scala: Boolean Algebra Internal DSL in Scala (aka fun with Unicode names ).
Also when it comes to External DSLs, Scala should be your first choice, and the reason behind that is the parser combinator lib, that makes writing compilers for new languages is really cool. You’d better follow this cool post to get a better idea about what Scala can do.

Interoperable with Java code

The JVM implementation of Scala have seamless integration with Java platform, actually many Scala types compiles down to Java types, so you can use Java libs safely. Also you can make some work between JVM languages like JRuby, Groovy, Clojure and others.
Here is a good post with examples.

Educational language

I had 2 habits that I kept practicing during the learning curve of Scala :

Both of these two habits made me gain more knowledge and increased the quality of my code through some good practices like: writing pure methods that has no side effect and focusing on the ‘what’ part of my code, leaving the ‘how’ one to language abstractions..


Scala was designed by Martin Odersky the man running the Programming Methods Laboratory (LAMP) group at Swiss Federal Institute of Technology in Lausanne (EPFL). Odersky was approached by Sun to write the Java 1.1 compiler, he was the lead developer of javac from Java 1.1 through Java 1.4. Also he is the guy behind Java Generics.
Scala is being maintained by Odersky and his team at EPFL. However there are other talented folks who helped shaping Scala over years, you can check the full list here.


Scala was inspired by many languages:

  • Most of the syntax is coming from Java and C#.
  • Other elements where adopted from Java such as: basic types, class libraries, and its execution model.
  • Its uniform object model was pioneered by Smalltalk.
  • Its idea of universal nesting is also present in Algol, Simula, and, more recently in Beta and gbeta.
  • Its uniform access principle for method invocation and field selection comes from Eiffel.
  • Its approach to functional programming is quite similar in spirit to the ML family of languages, which has SML, OCaml, and F# as prominent members.
  • Many higher-order functions in Scala’s standard library are also present in ML or Haskell.
  • Scala’s implicit parameters were motivated by Haskell’s type classes. Scala’s actor-based concurrency library was heavily inspired by Erlang.
  • The specific idea of treating an infix operator as a function and permitting a function literal (or block) as a parameter, which enables libraries to define control structures can be traced back to Iswim and Smalltalk.

Experts’ Opinions

This article is a very good one showing some for experts’ opinions regarding Scala language. Actually it has some surprises like James Strachan’s(creator of Groovy language) statement:

I can honestly say if someone had shown me the Programming in Scala book by Martin Odersky, Lex Spoon & Bill Venners back in 2003 I’d probably have never created Groovy

Also I have found these interviews to be very useful:

At the end of this point I like to sum things up:
I like Scala because it’s efficient, educational, has better concurrency model, and very good for writing DSLs.
I also want to share another secret with you:
I’m planning to write a book on Scala language, I have an idea at mind and would like to coauthor with any guy from the Scala camp, please ping me if you have the same attention as mine.

Real World Examples


Ruby Currying

Update: This post was updated to show the difference between Currying and Partial Functions.
Currying is a concept in Functional Programming that’s enabled by Higher-order functions. It’s best described as: the ability to take a function that accepts n parameters and turns it into a composition of n functions each of them take 1 parameter. Check this function f which takes 3 params x,y,z

f(x,y,z) = 4*x+3*y+2*z

Currying means that we can rewrite the function as a composition of 3 functions(a function for each param):

f(x)(y)(z) = 2*z+(3*y+(4*x))

The direct use of this is what is called Partial Function where if you have a function that accepts n parameters then you can generate from it one of more functions with some parameter values already filled in. Ruby 1.9 comes with support for currying concept(through the Proc#curry method) and this blog post is explaining how you can use it effectively.
I’m going to walk you through a simple example to explain the concept, however i need to mention few things:
1- The main example is taken from the free Scala By Example book(First-Class Functions chapter), however i have replaced recursion calls by simple upto iterators.
2- In Ruby 1.9 you can use block.(*args) just like you use*args) or block[*args] in Ruby 1.8, so i’ll stick to block.(*) notation.
3- I could have used the inject method, but i preferred readability to concise code.

Let’s start the simple tutorial by adding three methods:
1- A method to sum all integers between two given numbers a and b.
2- A method to sum the squares of all integers between two given numbers a and b.
3- A method to to sum the powers 2^n of all integers n between two given numbers a and b.

Cool, however if you focus on the 3 methods, you will notice that these methods are all instances of a pattern Σf(n) for a range of values a -> b. We can factor out the common pattern by defining a method sum:

Ok, but what about having the formal definitions for the 3 methods? How can we have those definitions out of the sum method? Well that’s the use of currying and partial functions, in our case we just need to pass the first param to the sum method to specify what type of sum is it:

That’s it! I hope I could clarify the use of currying, if not just add your comment here 😉

Ruby and Functional Programming

Ruby is known to support the functional paradigm. This article is going to walk you through the Functional Programming page on WikiPedia, to revise the general concepts of functional programming and to explain how Ruby supports them.
According to wikipedia, a functional programming can be described as follows:

In computer science, functional programming is a programming paradigm that treats computation as the evaluation of mathematical functions and avoids state and mutable data. It emphasizes the application of functions, in contrast to the imperative programming style, which emphasizes changes in state. Functional programming has its roots in the lambda calculus, a formal system developed in the 1930s to investigate function definition, function application, and recursion. Many functional programming languages can be viewed as embellishments to the lambda calculus.

That’s a clear definition, however and if it’s not, the following walk through some concepts of functional programming should result in a better understanding:

Pure functions

In practice, the difference between a mathematical function and the notion of a “function” used in imperative programming is that imperative functions can have side effects, changing the value of already calculated computations. Because of this they lack referential transparency, i.e. the same language expression can result in different values at different times depending on the state of the executing program. Conversely, in functional code, the output value of a function depends only on the arguments that are input to the function, so calling a function f twice with the same value for an argument x will produce the same result f(x) both times. Eliminating side-effects can make it much easier to understand and predict the behavior of a program, which is one of the key motivations for the development of functional programming.

Pure functions support the mathematical definition of a function:

y = f(x)

Which means:
1- A function should return the same exact value given the same exact input.
2- A function does one thing exactly(has one clear mission), it has no side effects like changing some other value or write to stream or any other mission rather than its assigned one.

In fact Ruby doesn’t force you to write pure functions, but certainly it helps you to do so. Actually exercising yourself to write in pure functional style when possible helps you really in many ways:
1- It makes your code clean, readable and self-documenting.
2- It makes your code more “thread safe”
3- It helps you more when it comes to TDD.

Let’s have a look on how Ruby helps you do Pure functional code:

The ! symbol

Most of Ruby programmers know the ! symbol that comes at the end of method names like gsub!, merge! and many other methods. The ! symbol means: “Use it cautiously”. However If you focus more, you will notice that most of time, the ! symbol means: “This is a method that has a side effect; it alters the object which is invoked on!”.

As you can see, the upcase! method is not a pure functional method cause it has a side effect, it changes the string itself. On the other hand, the upcase method is a pure functional one as it returns the corresponding value with no other side effects.

On all hows, it’s highly recommended that you stick to this convention of method naming when you code in Ruby.


Everything is evaluated as an expression in Ruby: literals, method calls, variables… even a control structure has a value. For example you can do this in Ruby:

But that is a weak use of Ruby’s power, instead you’d better do:

Return value

Ruby returns the last expression value as the return value of the method invocation, so you don’t need an explicit return statement.

Together, the auto returned value and evaluating code as expressions are indeed a big support for pure functional code as finally they both serve the fact of having a value out of your method.

Higher-order functions

Functions are higher-order when they can take other functions as arguments, and return them as results. This is done in Ruby using lambda and block logic. If you don’t know how to use blocks, please do yourself a favor and visit this comprehensive article by Robert Sosinski.

Blocks in Ruby can help you do very nice things, one of them is ability to add control structure like syntax to your code. Check the following example, where a loop control structure is being defined:

Internal DSLs is also one of the nice things that you can achieve with block syntax in Ruby.

Currying and Partial Functions

Higher-order functions enable Currying, which the ability to take a function that accepts n parameters and turns it into a composition of n functions each of them take 1 parameter. A direct use of currying is the Partial Functions where if you have a function that accepts n parameters then you can generate from it one of more functions with some parameter values already filled in. Ruby 1.9 comes with support for this concept. check the following example:

For extended example about currying, check Ruby Currying blog post by me 😉 .

Type systems and pattern matching

Pattern matching allows complicated control decisions based on data structure to be expressed in a concise manner. in simpler words, it’s a data structure based matching. Pure functional languages should support this concept, however and afaik this is still not supported in Ruby, but there are several trials to add this concept. check this blog post by Eric Torreborre.

Strict versus lazy evaluation

Strict evaluation always fully evaluates function arguments before invoking the function. Lazy evaluation does not evaluate function arguments unless their values are required to be evaluated. One use of Lazy evaluation is the performance increases due to avoiding unnecessary calculations.

However as the following example shows, Ruby use Strict evaluation strategy:

The third parameter of the passed array contains a division by zero operation and as Ruby is doing strict evaluation, the above snippet of code will raise an exception.


Iteration (looping) in functional languages is usually accomplished via recursion. Ruby doesn’t force you to recursion but it allows you to do so. However following recursion style has it’s own tax: Performance.
Ruby 1.9 comes with some “tail call optimizations”, more here.


1- As you can tell, Ruby helps you write in functional style but it doesn’t force you to it.
2- Writing in functional style enhances your code and makes it more self documented. Actually it will make it more thread-safe also.
3- The main support for FB in ruby comes from the use of blocks and lambdas, also from the fact that everything is evaluated as an expression.
4- Ruby still lack an important aspect of FP: Pattern Matching and Lazy Evaluation.
5- There should be more work on tail recursion optimization, to encourage developers to use recursion.
6- Any other thoughts?