Short List of the Greatest Inventions of all Time

1. Sliced bread (1928, Otto Frederick Rohwedder)
2. Ruby (1995, Yukihiro “Matz” Matsumoto)
3. HPricot (2006, Why the lucky stiff)
4. Ruby on Rails (2005, David Heinemeier Hansson)

What a relief! I *really* had the urge to tell everybody how cool HPricot is, just did not know the way yet – until now. The cosmic balance is somewhat restored now that I blurted out this post :-) .

Needless to say, you need to take this list with a tiny droplet of humor: Of course if we consider development time, amount and scope of offered solutions, innovation, community, book coverage etc. etc. then Rails is a clear winner (and anyway, the two players are not in the same league). However, HPricot is a great example of how a not-new-at-all thing can be made much more usable, fast and “heaps of fun to use” (really) just by clever design and usage of the right tools (and a dash of a cool programmer’s charisma). It is one thing to come up with a purple cow on a non-saturated market with lots of space for innovation, and a different story to do the same when everything has been already said and done. And _why did it. Again.

I am writing a (not so) small web extraction framework in Ruby (planned release XMAS 2006) which heavily relies on HPricot as the HTML query language – so I dare to say I know (at least some parts of) HPricot pretty well, yet it still keeps me totally amazed. What I like the most about it (besides that it is lightning-on-steroids fast compared to anything available for the same task, feature rich, reliable, stable etc. etc.) is that it takes the ‘principle of least surprise’ to the next level: I would call it ‘principle of almost no surprise’. If someone has a bit of knowledge about org.w3c.dom, XML, XPath, XSLT and/or has experience with other HTML/XML parsers/tools will have to refer to the documentation very rarely (of course there is a period of learning the basics and soaking into the HPricot-philosophy, but the learning curve is *really* steep).

Before I get to the proof that HPricot is able to solve the food problems in Africa or something, I need to cool down a bit :-) : HPricot is not for everyone and not for every problem. If you need complex XPath evaluation for instance, you will have to stick with the good old REXML (for now , at least – I read that _why will add more XPath support and other goodies in the future). In the present version, you won’t be able to evaluate things like axes (e.g. ancestor::html) or XPath functions (e.g. normalize-space) and not even XPaths with indices (like html/body/table[1]/tr[2]/td[5] – though I wrote a small script to remedy this problem temporarily.)

There are a lots of HTML-extraction related questions on the Ruby mailing list (like how to extract every table cell from a <tablle:> etc.) My advice is to alwways check out HPricot first: Sometimes it can be an overkill to use it (if you can get what you want with a simple regexp, for example) but usually it is the right tool to parse and query even the ugliest HTML pages out there- unless you need heavy XPath/XQuery machinery which is rarely the case in the real life.

What else do I need to add? Great job, _why. Thanks man.

Sometimes less is more

Update: A lot of people were disappointed that 10.minutes.ago etc. is not working in pure Ruby. Well, after executing the line require ‘active_support’ it does – I think this is a fairly small thing to do to enable these powerful features.

Every guide published on favorable writing principles emphasizes the power of brief and concise style. This is especially true in the case of technical texts, and in my opinion, in the case of well-designed programming languages as well.

Note the word well-designed. I did not say in the case of any (programming) language, since that would just not be true: conciseness can come at the cost of readability. (If you ever tried to read kanji, you know what I am talking about ;-) . However, I am claiming that in the case of a really well-designed programming language, succinctness helps readability, reduces bloat and leads to easier and faster understanding of the code. In my experience, the amount of boilerplate code to write is decreasing proportionally with the terseness of the programming language, ultimately leading to a coding style where you (nearly) don’t need to write boilerplate at all.

I will demonstrate this on a few Java vs. Ruby code examples. However, this is NOT a Ruby-bashing-Java article, but a few examples of idioms and interesting constructs; C++ vs Haskell or Lisp could serve equally well (sometimes even better), but since I am currently working with Java and Ruby on a daily basis, it is easier for me to use them.

If you are a pro Ruby and/or Java programmer, and/or you think the article is too long for you, please jump to the “Random Code Snippets” section.

Possibly the most straightforward reason why Ruby code is more readable even in shorter form is that really everything is an object [1] in Ruby-land. For example in Java, primitives need wrapper classes to ‘become’ objects., while in Ruby they are first class objects on their own. This makes constructs like

10.times { print "ho" }  #=> "hohohohohohohohohoho"

or (will output the same string)

print "ho" * 10 #=> "hohohohohohohohohoho"

possible.

There are a handful of other reasons which make Ruby more readable and elegant, but before I get bogged down in the explanation too much, let’s see the examples!

Whetting your appetite

In the first part I will describe some basic constructs which would make the life of any Java developer much easier. These techniques are neat, but they are not using any really sophisticated stuff yet: I will try to take a look at those in the next bigger section.

The empty program

Java:

class Test
{
    public static void main(String args[]) {}
}

Ruby:

   

I did not forget the Ruby snippet; You can not see anything there because actually a Ruby program doing nothing is exactly 0 characters long.
On the other hand, the Java version is slightly longer. I is kind of weird to explain to a newcomer what do ‘class’, ‘public’, ‘static’, ‘void’, ‘String’, the [] operator and several braces here and there mean, and why are they needed if the program does literally nothing

Fun with numbers

Note:For some of the next examples you will need to use Rails Active Support.

Java:

if ( 1 % 2 == 1 ) System.err.println("Odd!") #=> Odd!

Ruby:

if 11.odd? print "Odd!" #=> Odd!

Does not the first example make more sense (even for a non-programmer)?. I believe it does. More of this type:

Java:

102 * 1024 * 1024 + 24 * 1024 + 10 #=> 106979338

Ruby:

102.megabytes + 24.kilobytes + 10.bytes #=> 106979338

OK, maybe this is an unfair comparison since Java does not have (?) those functions. However, the point is that even if it had,
the best I could come up with would look like:

Util.megaBytes(102) + Util.kiloBytes(24) + Util.bytes(10) #=> 106979338

Which is far from the elegance and readability of the Ruby example.

In the next example we will assume that we have a Java function similar to ordinalize in Ruby.


Java:

System.err.println("Currently in the" + Util.ordinalize(2) + "trimester");

Ruby:

 print "Currently in the #{2.ordinalize} trimester"    #=> "Currently in the 2nd trimester"

In this example we can observe variable interpolation: anything wrapped in #{} inside double quotes gets evaluated
and substituted in the string, providing a more readable form without a lot of + + Java constructs (which is cool mainly if you have more variables inside the double quotes).

Dates

In my opinion, handling dates and times is a great PITA in Java, especially if you are implementing some complex code.

Java:

System.out.println("Running time: " + (3600 + 15 * 60 + 10) + "seconds");

Ruby:

puts "Running time: #{1.hour + 15.minutes + 10.seconds} seconds"

Java:

new Date(new Date().getTime() - 20 * 60 * 1000)

Ruby:

20.minutes.ago

Java:

Date d1 = new GregorianCalendar(2006,9,6,11,00).getTime();
Date d2 = new Date(d1.getTime() - (20 * 60 * 1000));

Ruby:

20.minutes.until("2006-10-9 11:00:00".to_time)

I think you do not have to be biased towards Ruby at all to admit which code makes more sense instantly…

I have recently found a very cool way of parsing dates in Ruby: using Chronic. However, I would not like to present it here since it is not a feature of the language, ‘just’ a nifty natural-language date parser [2].

A little bit more advanced stuff

Classes

Java:

Class Circle
  private Coordinate center, float radius;

  public void setCenter(Coordinate center)
  {
    this.center = center;
  }

  public Coordinate getCenter()
  {
    return center;
  }

  public void setRadius(float radius)
  {
    this.radius = radius;
  }

  public Coordinate getRadius()
  {
    return radius;
  }
end;

Ruby:

class Circle
  attr_accessor :center, :radius
end

Believe it or not, the two code snippets are absolutely equal; The getter and setter methods in Ruby code are generated automatically, so not only you do not have to write them, but they are not even there to clutter the code.

I have seen argumentation from Java guys that stuff like this (i.e. the public static void main … thing, getters/setters and other boilerplate code) can be generated with any decent GUI like Eclipse (or by tools like XDoclet etc) is a non-issue. Well, as for their generation, let us say this is true. But for the readability of code it is absolutely not!

For example. take getters/setters: Every variable in Java ads 8 more lines of code (not counting the lines between the function declarations) compared to the Ruby :attr_accessor idiom. That is, a simple class definition having 10 fields in Java will have 80+ lines of code compared to 1 lines of the same code in Ruby. For me, this definitely means a big difference.

Arrays (and other containers)

This section was inspired by a blog entry by Steve Yegge.

Arrays are interesting citizens of Java: They are not really objects in the “classical” sense , so they have very limited functionality compared to first-class Java objects. On the other hand, they are offering a huge advantage over the other container classes: they can be easily initialized.


Java:

String languages[] = new String[] {"Java", "Ruby", "Python", "Perl"};

instead of

List<String> languages = new LinkedList<String>();
languages.add("Java");
languages.add("Ruby");
languages.add("Python");
languages.add("Perl");

which is kind of lame when you quickly need to hack up some testing data.

However, they have also some serious problems: you have to define the number of the elements upon construction time, like so:


Java:

String someOtherLanguages<String>[] = new String[15];

which sometimes really cripples their functionality. [3]

How does this work in Ruby? Let’s see on three different examples (All three code snippets provide the same result):

Ruby:

stuff = [] #An empty array - as you can see there is no need to define the size
stuff << "Java", "Ruby", "Python" #Add some elements
#Initialize the array with the values
stuff = ["Java", "Ruby", "Python"]
#Yet another method yielding the same result
stuff = %w(Java Ruby Python)

In my opinion, these forms (especially the last one) are more straightforward and can save a lot of typing.

Another major shortcoming of Java arrays is that besides the [] operator you have only the methods inherited from Object and a single instance variable : length [4]. This means that even essential functionality like sorting, selecting elements based on something etc. has to be done via a ‘third party’ function, like this:


Java:

Arrays.sort(languages);

which seemed quite normal to me when I have been learning Java and have had no previous experience with dynamic languages, but now it looks kind of annoying.

Another Java-container-woe compared to Ruby is that in Java, an array is an array. A list is a list. A stack is a stack.
If you are wondering what the hell I am talking about, check out these Ruby code snippets:

Ruby:

stuff = %w(Java Ruby Python)
#Add the string "Perl" to the array
stuff << "Perl"
#Prepend the string "Ocaml" 
stuff.unshift "Ocaml"  
=> ["OCaml", "Java", "Ruby", "Python", "Perl"]
#Use the array as a stack
stuff.pop 
=> "Perl"  #stuff is now ["OCaml", "Java", "Ruby", "Python"] 
stuff.push "C", "LISP"
=> ["OCaml", "Java", "Ruby", "Python", "C", "LISP"]
#Update C to C++ 
stuff[4] = "C++"
=> ["OCaml", "Java", "Ruby", "Python", "C++", "LISP"]
#Remove the fisrt element
stuff.shift
=> "OCaml" #stuff is now ["Java", "Ruby", "Python", "C++", "LISP"] 
#Let's just stick with Java and Ruby - slice out the  rest!
stuff.slice!(2..4)
=> ["Python", "C++", "LISP"] #stuff is now ["Java", "Ruby"]

As you can see, the Ruby Array class offers functionality that could be achieved only by mixing up several Java containers into one (to my knowledge, at least) [5]. In practice, this usually speeds things up a lot.

Another thing that really annoys me when using containers in Java is the lack of this functionality:

Ruby:

stuff = ["OCaml", "Java", "Ruby", "Python", "C++", "LISP"]
#Lua is just gaining steam, add it to the 7th place
stuff[7] = "Lua"
=> ["OCaml", "Java", "Ruby", "Python", "C", "LISP", nil, "Lua"]

i.e. that if I am adding an element to an index which is bigger than the size of the array, the empty space inbetween is filled with nils. Now seriously, who would not exchange this for the Java behaviour (an IndexOutOfBoundsException is thrown) – after all, if I would need this functionality (which is VERY seldomly the case) in Ruby, I could check it myself and raise an exception if I don’t like what I see.

I wanted to write a bit about differences between hashes and files in Ruby and Java, but the post is already longer now then I wanted it to be so I guess I will just show some concrete code snippets to conclude.

Random Code Snippets

In this section I would like to present some real cases I have been solving with Ruby recently. Since I am still new to Ruby, I was totally amazed just how much more simpler, shorter yet much more understandable the code can be in Ruby compared to Java.

Files and Regular Expressions

As Bruce Eckel once put it, In Java, it’s a research project to open a file. Well, I have to agree. Maybe I am the only one Java programmer (besides Bruce) who – even after using Java professionally for five years – still can not write to a file without using google first. Maybe I should learn it one day?

Regular expression support in java is OK (at least one does not have to use external packages as in the pre-1.4 era), however, compared to Ruby the syntax is quite heavy.

Let’s see a demonstration on the following task: Open the file ‘test.txt’ and write all the sentences to the console (one sentence per line) which contain the word ‘Ruby’. First, the Java solution:


Java

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Test 
{
	public static void main(String[] args)
	{
	    try {
	        BufferedReader in = new BufferedReader(new FileReader("test.txt"));
	        StringBuffer sb = new StringBuffer();
	        String str;
	        while ((str = in.readLine()) != null) 
	          { sb.append(str + "\n"); }	        
	        in.close();
	        String result = sb.toString();
	        Pattern sentencePattern = Pattern.compile("(.*?\\.)\\s+?");
	        Pattern javaPattern = Pattern.compile("Ruby");
	        Matcher matcher = sentencePattern.matcher(result);
	        while (matcher.find()) {
	            String match = matcher.group();
	            Matcher matcher2 = javaPattern.matcher(match);
	            if (matcher2.find())
	            	System.err.println(match);
	        }
	    } catch (IOException e) 
	      {
	    	e.printStackTrace();
	      }		
	}
}

It is quite straightforward what this relatively simple code snippet doing – but if this is straightforward, what should I say about the Ruby version?

Ruby

File.read('test.txt').scan(/.*?\. /).each { |s| puts s if s =~ /Ruby/ }

Well, umm… I guess this example quite much expresses the point I am talking about from the beginning: sometimes less is more, a.k.a. Succinctness is Power!

Again, I wanted to show much more examples, but I have the feeling that since the article is already too long, no one would read it :-) It is a big pity since I did not even talk about hashes, blocks, closures, metaprogramming (well, I will mention it briefly in the last (really :-) ) example) and other goodies – maybe in part 2?

If this is still not enough…

Although I find it very easy and natural to express a lots of things in Ruby, the language can not offer anything I would ever need. However, there is a powerful concept to invoke in such situations, called metaprogramming.

A few days ago I needed to test some algorithms on trees, so I needed to hack up a lot of tree test data. Here is how I would go about this in Java using the example below (let’s assume in both languages that we have a simple data structure Tree):

               a
            /      \
          b         c
         /  \      / | \
        d    e    f  g  h

Java

Tree a = new Tree("a");

Tree b = new Tree("b");
Tree c = new Tree("c");
a.addChild(b);
a.addChild(c);

Tree d = new Tree("d");
Tree e = new Tree("e");
b.addChild(d);
b.addchild(e);

Tree f = new Tree("f");
Tree g = new Tree("g");
Tree h = new Tree("h");
c.addChild(f);
c.addChild(g);
c.addChild(h);

Another possibility would be to create an XML file with the description of the tree and parse it from there. This solution is even more convenient since though you have to write the parsing code, you just have to edit an XML file once it is written. One possibility how the tree of this example could look something like


XML

  <node name="a">
      <node name="b">
          <node name="d"/>
          <node name="e"/>
      </node>
      <node name="c">
          <node name="f"/>
          <node name="g"/>
          <node name="h"/>
      </node>
  </node>

The latter solution is quite cool. After all you do not need to write any code, just alter the XML file and that’s it.

Now let’s see the Ruby solution I came up with:

Ruby

tree = a {
            b { d e }
            c { f g h }
          }

Well… suddenly even the XML file seems too heavy, does not it? :-) Not to mention the fact that the latter example is pure Ruby code – there is no need to open an external file and parse it – you just run it and the variable tree will contain your tree. That’s it.

Of course Ruby can not handle this code as it is – for this we need to invoke some metaprogramming magic.
[6]

Metaprogramming is a way to drive Ruby with Ruby. Java (especially J2EE) is usually driven by XML (which is not always really a good thing in my opinion) As you could see, Ruby is driven by Ruby instead :-)

This example merely scratched the surface of Ruby’s possibilities through metaprogramming. However, as with the other examples, my goal was not to advocate a concrete pattern/method over a different one, but rather to show how a specific toolset can change the way of thinking about the task at hand, and the way of code design/implementation in general.

Final thoughts

When I was a child, I spoke as a child, I understood as a child, I thought as a child: but when I became a man, I put away childish things. – The Bible, I Corinthians 13:11

This thought pretty well expresses how I felt about Java/C++/(substitute any non-dynamic language here) when I came to know (some of) Ruby’s true dynamism and expressive power through terse yet powerful idioms which transformed my whole thinking about programming. Of course I do not claim that I ‘became a man’ because that’s still a very long way to go, but still, even with my very limited knowledge of Ruby, the way to express things in Java/C++ now seems… well… childish ;-) . [7]


Creating a site on online tutorials is not a completely bad idea. One should include courses for 642-054, 642-054, 642-176, ruby on rails, cissp certification. If you have the knowledge for creating the tutorials, the rest is very simple. By using dot5hosting company’s site you can purchase a web hosting package that is economical. Even dedicated servers can be found for low prices. Then through the use of ip telephony one can directly reach its potential clients. Other internet marketing methods should also be considered to create awareness the site.


Notes

[1] I wonder whether this déjà vu will happen to me in the future once again: I have had this ‘Wow, everything is an object’ feeling when coming from C++ to Java; Then after coming from Java to Python; and most recently, after coming from Python to Ruby. Back


[2] Some examples that Chronic can handle:

  summer
  6 in the morning
  tomorrow
  this tuesday
  last winter
  this morning
  3 years ago
  1 week hence
  7 hours before tomorrow at noon
  3rd wednesday in november
  4th day last week

Kudos…
Back


[3] In the previous array initialization example this was not needed since it is trivial when all the elements are stated beforehand.Back


[4]which somewhat confusing given that all the other containers use the method size() (and not a field!) to determine the count of elements. To nicely mesh with the confusion, the String object provides the method length() (and not a field, as with array) to query the number of characters… Back


[5] I mean it is not possible to construct any container – other than an array – with literals, you can use the [] operator on arrays only, you can not get the i-th element of a stack etc. Back


[6] The code I have been using to accomplish this task relies on the method_missing idiom:

class Object
  @stack = []
  @parent = nil

  def method_missing(method_name, *args, &block)
    tree = Tree.new(method_name)
    @parent.add_child(tree) if @parent != nil
    if block_given?
      @stack ||=[]
      @parent = tree
      @stack.push @parent
      yield block
      @stack.pop
      @parent = @stack.last
    end
    tree
  end
end

Back


[7] This does not necessarily mean that Java is bad and Ruby is good – just that it was the ‘Ruby way’ that struck a chord in me after trying/playing around with programming in many programming languages. Many of the features I adore in Ruby are there in Java as well, but they did not ‘came through’ whereas with Ruby there was a point of enlightenment when I really understood a lot of generic, non-language specific principles. Back

Evaluating XPaths with indices in HPricot

Currently I am working on a Ruby web-extraction framework (more on this in a future post) and I have chosen Hpricot for the HTML parsing and XPath evaluation. So far, it seems to be the perfect choice – it is lightning fast (nothing I have encountered so far – REXML, Htree, RubyfulSoup – was even near in terms of speed), very intuitive to use, and it simply works for nearly everything you will need for day-to-day tasks.

However, since my Web-extractor is relying on XPath very heavily, sometimes I need things not included in the ‘nearly-everything’ bag of goodies – but so far I have always managed to come up with a solution. Last time it was the evaluation of XPaths with indices. This is what I hacked up:

def to_hpricot(xpath)
  "#{'(' * (xpath.split(/\d+/).size-1)}" +                 
  xpath.gsub(/\d+/) { |num| (num.to_i - 1).to_s }. 
        gsub(/\/(.*?)\[/) { |p| "/'#{$1}')[" }            
end

Whew, that's ugly - but it works quite well. Let's see a simple example:

doc = Hpricot("<p>A<b>very</b>simple<b>
  <i>small</i>test<i>document</i>.</b>Very cool.</p>")

eval(to_hpricot('doc/p[1]/b[2]/i[2]')) 
=> {elem <i> {text "document"} </i>}

OK, it is really just a hack – it does not consider special cases, does not handle anything besides indices (i.e. no axes, @’s or anything) etc. – but anyway this is hopefully just a temporary solution and _why will add evaluation of indexed XPaths to Hpricot soon. There would be at least one HPricot user who would be really delighted about it :-)

The Sadly Neglected Pickaxe-killer

I have just finished reading Ruby for Rails: Ruby techniques for rails developers from David A. Black. Here is my (WARNING: highly opiniated) review…

I have been a Python fanatic for quite some time, and decided to give Ruby a shot. After some googling, I found most references pointing to a book called the ‘Pickaxe’. Quite a strange name for a programming book, thought to myself, but picked it up nevertheless. I have been instantly converted after a few dozen pages – mining Ruby with the pickaxe was an awesome experience! Since then, I have finished reading the second edition and became a Ruby enthusiast.

After lurking around a bit, I have learned that the common standpoint is that every newcomer/beginner should grab a copy of the Pickaxe to get started. Based on my previous, positive experience I could not agree more – until I came across R4R.

Ruby for Rails is awesome: The technical depth is just right to not distract beginners, yet detailed enough for even the more advanced readers. I did not skip a single page (though years of programming experience and tons of similar programming books I came across during that time could allow me) and finished reading it in no time.

I could write some more about how cool this book is (and it would deserve every bit of it), but I think you can read about that just anywhere (a nice review can be found here), so I would like to point out something different: If we consider the Pickaxe THE book for newcomers, then IMHO R4R is a Pickaxe killer.

Don’t get me wrong: I am a great fan of the Pickaxe, which is another very high-quality technical book – but if someone wants to apply the ‘right tools for the right job’ principle, I think newcomers who already decided to learn Ruby should grab Ruby for Rails. Programming Ruby’s Part I is absolutely well suited to get the ‘feeling’ of Ruby, and it’s next chapters are great to learn the advanced stuff – however in my opinion, the leap between the first and the next chapters is too big for an absolute beginner. Ruby for Rails is there to fill this gap.

Maybe someone might not advice this book to a newbie eager to learn Ruby, since it has ‘Rails’ in it’s title. However, R4R is still primarily a Ruby book, and while I found the Rails parts to be very helpful, I can recommend it to anyone who would not like to learn Rails at all – though the full potential of the book comes through if one would like to learn both.

Conclusion: Ruby for Rails is an awesome book on Ruby. If you are beginner, would like to get a solid understanding of the Ruby principles, or your goal is to polish up your Ruby knowledge to grasp the Rails framework – R4R was made just for you! Check it out – you won’t be disappointed.

Announcing screen-scraping series

I am planning to write a series of entries on screen scraping, automated
Web navigation, deep Web mining, wrapper generation, screen scraping from
Rails with Ajax and possibly more, depending on my time and your feedback.
Since these entries are going to be longer, I will be posting them to
separate pages, and announce them on my blog.

The first article is ready, you can read it here.

It is an introduction to screen scraping/Web extraction with Ruby,
evaluation of the tools along with installation instructions and examples.

Feedback would be appreciated (leave your comment here/on the article page, or
send me a mail at peter@[name of this site].com), I will update/extend the
document and publish new ones based on your feedback.

Programming is hard

Programming is great fun (mainly with Ruby ;-) . However, this statement does not contradict with the fact that sometimes programming can be also hard. I came across a nice site today which can offer some help in these moments: Programming is hard. Judging from the size of Ruby/Rails/ActiveRecord tags (there is even a script.aculo.us tag!) it seems that it has a nice dose of Ruby/Rails stuff – solutions for common problems and also links to tutorials, frequenty asked nuby questions etc. Be sure to check it out!

Gems or Snakes?

After being a very happy Python programmer for 2 years, i have switched to Ruby a few months ago, and though Python is still
my 2nd favourite language, i have never thought of going back to it for a second. In fact, this feeling was so
natural that i did not even think about it’s reason for some time.

If someone compares these two languages just from the technical point of view, the difference is de facto non-existent.
Both languages are built on similar principles, both of them serve essentially the same purpose. What is the secret
sauce of Ruby then? Why did i get attracted to it immediately, past the point of no return? Here are a few points that came to my mind:

‘He is the ONE

  • If a beginner stumbles onto Ruby, there is ONE book he will be pointed to. The PickAxe.
  • If somebody asks which web framework should he use in Ruby, he will be pointed to a specific ONE: Ruby on Rails.
  • If he asks for a starter book on RoR, he will be advised to buy the coolest ONE: Agile Web Development with Rails.
  • If he asks for a discussion list/newsgroup, he will be pointed to the only ONE: ruby-talk.
  • If he looks for an XML processing library, he will be pointed to the standard ONE: REXML.

The list could go on and on…

A Rubyist with no previous Python experience may ask ‘Well, what’s so cool about this? It’s normal’. Well, i am glad that in Ruby is, but Python is a different story. I think it lacks the books like PickAxe and Agile Web Development with Rails, and also the community is divided up between Django, Turbogears, Pylons, Subway, … and the other dozen of web frameworks.


nice application of the DRY principle :-)

Rolling on Rails

If you would ask random people to summarize in one point why Ruby is so popular today, i am quite sure most of them would say ‘because of Ruby on Rails’. This framework is really that cool, believe it or not. Some people are already apostrophing it ‘the language/framework of web2.0′, pointing out that Rails is the next big thing in the web space.

Spread the word

A programming language is essentially a bunch of boring definitions: Some grammar, rules, constructs etc. Even if it is very very cool, no one will notice it unless it is evangelized. That’s why great stuff needs great evangelizators: Perl+Larry Wall. Microsoft+Bill Gates. Ruby+DHH.
To follow the logic, i should have written Ruby+Matz. But i would not write Matz, just as i would not pair Python with Guido van Rossum in this sense. These smart gentlemen are really good at language crafting, but the analogy with Perl/Larry Wall stops here. Fortunately Ruby has a great evangelizator, too, although an ‘indirect’ one: David Heinemeier Hansson, who, in my opinion made Ruby really popular through the Rails framework.

Community

After a few dozen of mails, i have much much better experience with the ruby-talk ML than with python-tutor. Of course one should not judge based on a few dozen mails, but the Ruby community feels to me like a big family, whereas the Python community is more like a bunch of engineers in white suits. Matz’s ‘Why does Ruby suck’ kind of style appeals me much much more than Python’s agnostic approach – ‘Maybe it is not even sure that there is a problem – first you should define what do you think the term ‘problem’ means, anyway’ etc. Of course this rigorous style may appeal to some – but not for me.

Integration [with Java]

From the JRuby page:
[JRuby is] A 1.8.2 compatible Ruby interpreter written in 100% pure Java

On the Jython page, i could not even find the compatibility with java – but according to the page, “The final release of Jython-2.1 occurred on 31-dec-2001″

For comparison: Ruby 1.8.2 is almost the latest stable, and JRuby’s last release was on 27-march-2006. JRuby makes also some Rails integration possible already, and the authors are focusing on other J2EE issues like calling EJBs etc.

I think in a world where Java is the king of the hill (at the moment), Java integration can be a deciding factor.

Goodies

T-shirts. Cofee Mugs. Baseball caps. Other kind of good-for-nothing junk – must haves for all geeks! Of course with their favourite stuff on it. Well, after looking on cafepress.com (and on google in general) Ruby is a winner again when compared to Python.

The list could continue on, but since this entry is already too long i am going to stop here ;-) Of course, as everything on this blog,
this article reflects my opinion, my perception of Ruby/Python. If you think Python is better suited for you, i am not arguing or anything – it would not make sense. However, i think Ruby has much more potential to become widely accepted as a mainstream language right now than Python – and this, besides that i like to code in Ruby much more, will keep me in the Ruby camp for a long-long time…

WWW::Mechanize problem (probably Ubuntu only(?))

I am working on a small screen-scraping utility written in Ruby, and since I have been working previously with RubyfulSoup, I wanted to give WWW::Mechanize a try this time.

So i have installed the WWW::mechanize gem:

sudo gem install mechanize

I wanted to try a ‘Hello world’ application first, to see wheter it works. Here are some official examples (click on ‘Examples’). I Copy&pasted the first one, run and got the following error:

/usr/local/lib/site_ruby/1.8/rubygems/custom_require.rb:21:in
`require__': no such file to load -- net/https (LoadError)
from /usr/local/lib/site_ruby/1.8/rubygems/custom_require.rb:21:in `require'
from /usr/lib/ruby/gems/1.8/gems/mechanize-0.4.4/lib/mechanize.rb:15
...
...

After some googling i have found the answer: I had to install libopenssl-ruby, and the error was gone.

I wonder if you have to install this amount of additional packages on other distributions also? From the time I am using Ruby/Rails I did not have other distro than Ubuntu, but back in my Python days I have been running on gentoo and I don’t remember such problems. Ubuntu is really very cool, but it seems you have to know well which packages do you need and install them manually when it comes to coding/development…

Getting Ruby on Rails up and running on Ubuntu Dapper

I have just installed Ubuntu Dapper Drake Flight 6 on my desktop machine, and because I had had different problems to install Rails from scratch several times (even the recent session was no exception), I have decided to write a step-by-step guide, which assumes a clean, fresh install of Ubuntu ( i.e. at this point you do not even have Ruby on your machine) and leads you through installing Rails and creating a working test application.
Why is this writeup better than any other how-to-install-rails tutorials out there?

  • Because it will tell you to install really just what you need, not 50 packages more
  • It will also show you how to configure the DB and other things to really make Rails work, not just installed

Let’s get started!
Note: Some people asked if this manual is for dapper only. I would say mostly yes, because i have had different problems on breezy (for example i had to compile ruby-mysql driver manually). Its not entirely impossible that it will work with breezy – but then you will have to make sure that the packages are the same version as assumed here (e.g. MySQL > 5 etc.)

Part I: Installation

Prepare the system for the installation

  • Check /etc/apt/sources.list – make sure you have access to the ‘universe’ packages by uncommenting them:
deb http://us.archive.ubuntu.com/ubuntu dapper universe
deb-src http://us.archive.ubuntu.com/ubuntu dapper universe
  • Refresh apt packages to make sure you get the most up-to-date stuff:
sudo apt-get update

Install Ruby related packages

  • Install Ruby essentials: ruby, irb, rdoc, ri
sudo apt-get install ruby rdoc ri
  • Install gems: download, unpack, install
go to http://docs.rubygems.org/
download rubygems-0.8.11.tgz (or the latest version)  tar -xzvf rubygems-0.8.11.tgz
cd rubygems-0.8.11/
sudo ruby setup.rb

MySQL installation and configuration

  • Install MySQL:
sudo apt-get install mysql-server
  • Install ruby MySQL bindings
sudo apt-get install libmysql-ruby

Install Rails

sudo gem install rails --include-dependencies

Part II: Configuration

Setup the DB

  • Add an user, create a test database and grant acces for the user
mysqladmin -u root create test_development
mysql -u root

Into the db shell, write the following commands:

create user 'batman'@'localhost' identified by 'robin';
grant all on test_development.* to 'batman'@'localhost';

Don’t forget to replace the username/password (unless you happen to be Batman of course – in this case i suggest to use a different password since this can be guessed easily by social engineers ;-)

Create and test the rails app

  • generate the app files

Lets denote your working directory (the root directory where your future rails project s will reside rails_projects).

cd rails_projects
rails test
  • edit config/database.yml
cd rails_projects/test 
vim config/database.yml
  • It should look like this:
development:
adapter: mysql
database: test_development
username: batman
password: robin
host: localhost
  • generate a dummy model
ruby script/generate model Dummy
  • edit the migration file
vim db/migrate/001_create_dummies.rb
class CreateDummies < ActiveRecord::Migration
def   self.up
  create_table :dummies do |t|
    t.column :foo,    :string
    t.column :bar,    :string
  end
end

def self.down
  drop_table :dummies
end
end
  • run the migration
rake db:migrate
  • generate a simple maintenance app
ruby script/generate scaffold Dummy Admin
  • start the server
ruby script/server

Point your browser to http://localhost:3000/admin to see the result.
If you have any problems, please leave a comment, i will try to help you.

Internet contains huge number of opportunities to earn money online. Simply create a site that you think has the potential to sell hot items using ruby on rails. Register a relevant domain name and purchase a web hosting service through hostgator, one of the better web host out there today. Get a internet connection through one of the wireless internet providers to upload your site. Work on search engine optimization to get a better traffic and also use affiliate marketing program for the same reason. Finally get a free voip phone service to contact customers directly. The pc to phone system is the most effective method of marketing.

Fresh Meat – First Impressions of Agile Web Development with Rails (2nd ed) and Ruby for Rails

I have bought both books recently. Maybe it is a little bit early to write a review since I am through just a few chapters in both, I have been so impressed that I had to write a (not so) short entry at least ;-) !
I have been using C++/Java/Python for years, and have been reading as much books on every possible aspect of development with these languages as I could get. In my oppinion Ruby and Rails are absolutely superior to all of these languages (and their web frameworks/related things) in this context – The Pickaxe, AWDwR and R4R cover nearly all the things you will ever need to learn the language and Rails – and not just understand the ‘how’, but also the ‘why’, learn best practices, coding and development methodologies from code style to design issues, related technologies and more.

The point is not (only) this, since you can do the same with a few Java books (although not 3, but something like 10), however you will have harder time with Python (There is a Django book on the way, and also the Turbogears guys are publishing one but neither are out yet – but no PickAxe, AFAIK) – however, the point is, based on the experiences i have had with C++/Java/Python books that neither of them are so well written/to the point/effectively explained/well built up than the Ruby ones. Simply put: The Ruby/Rails books are the best technical books i have ever read on programming and (web) development.

AWDwR 2nd ed Agile Web Development with Rails, Second Edition
I begun to develop the depot application with the first edition about a month ago, and since I was new to both Ruby and Rails, I have thought: WOW! I was about halfway through the depot chapter when i have noticed the announcement about the Second Edition a few days ago. I have purchased the pdf version immediately, and I am quite sure this purchase has to be listed in my ‘Best value for money TOP 10′ list (along with R4R ;-) .

It was a very refreshing experience to code the depot application from the first edition, but as I got into Rails more and more, I have felt that there are some small gaps here and there. On the mailing list, everybody was talking about migrations (i had no clue that time about them), helpers, AJAX/RJS, REST and other stuff i was not able to find during the depot development, and though the amount of information and level of coolness was overwhelming, I still sensed there is still even more than this.

After redoing the depot application with the second edition, all these things (among others) are finally there! You get all the goodies from the very beginning (migrations, writing your own helpers, AJAX etc) so you do not have to search the Web for the newest features anymore.My overall impression was that the small annoying things are gone, the good things are even better, thus the overall experience of reading the book/following the code is even more delightful! I can’t wait for the next chapters! This upgrade definitely rocks! Well done Dave et al.

Ruby for Rails Ruby techniques for Rails developers
I have gone through just the firs three chapters so far, and though they are supposed to be introductory chapters (entitled How Ruby works, How Rails works and Ruby-informed Rails development) I could not believe how much info I got out of them. I have to say that I am a totally mega-n00b to both Ruby and Rails, but still, I have gone through the PickAxe and half of AWDwR, 1st ed, i am a regular reader of Ruby-talk and the RoR mailing lists, so on the other hand I have some basics, and still these chapters provided me a lot of new insight.

The book (or at least the first three chapters) is extremely well written, easy to grasp yet the breadth of knowledge is really impressive. It really shows the design philosophy, logics, inner working of the things rather than just providing some theory with a few examples, or being a ‘yet another Ruby/Rails book’ in any way. If you would like to find out how the things really work, and why they work that way, rather than just be a developer who can do this and that with Rails, definitely check this book out!

R4R

There was a kind of flamewar on the Ruby on Rails mailing list about the pricing of the AWDwR second edition: One group argued that they should get some discount because they own the first edition, and the other party did not agree with this standpoint. Well, personally I am definitely in the second group – I did not hesitate to buy the PDF for a moment – I can understand (but not support in any way) the arguments of the first group, but I would gladly pay for this book even $100, not $20+, regardless of the editions I own. (And just FYI, I am a full time Java developer and though I would like to get a Ruby (on Rails) job ASAP, due to different constraints RoR is and will be just my hobby for some time)

Just my 2c.

Announcing rubychallenge.com

About a month or so ago, we begun to work on a new ruby puzzle site entitled rubychallenge.com with Alex Combas.

Some people may think after reading this line: “Yet another ‘not pron’ or ‘pythonchallenge.com’ clone”. Well, i would not say we did not borrow some basic concepts from these great puzzle sites, but our final product will have not very much in common with them: There will be programming puzzles on rubychallenge.com, and the domain suffix is equal with that of the pythonchallenge site. However, the analogy stops here. Rubychallenge will offer an entirely different programming/game/puzzle experience compared to all the similar sites out there, both in terms of game concepts and mechanics, as well as entirely unique site structure/design.

We have tons of ideas in our wiki already, and right now we are fledging out which ones to implement. Alex just set up a working development environment, so after ironing out some ideas crucial to begin, we might even write some code soon ;-)
We would like to come up with a presentation/demo page as soon as possible, and possibly a development blog to inform you what’s going on. At some point we would like to incorporate some beta testers, so stay tuned!

Java and Ruby (on Rails)

Being a professional Java programmer myself, i collected some links that might bridge the gap for Java programmers who would like to take a peek at Ruby:

Introductory materials

Java – Ruby integration

  • JRuby – A 1.8.2 compatible Ruby interpreter written in 100% pure Java. Charles Oliver Nutter, one of the JRuby developers in a discussion claimed that “We’re currently working to make JRuby more EJB and J2EE-friendly, so you’re certain to see more of these opportunities.”

The question from the top of every RoR/Java FAQ:

Ajax Goodies:

Not exactly java, but nice Rails+Ajax technology showoff