Archive for January, 2006

Ruby Blocks 101

One of the difficulties you might have with jumping into Ruby on Rails is that you need to learn the Ruby language (yes, you do 😉 ). And if you come from the PHP background as I am, the single weirdest thing in Ruby would be the notion of blocks. I have never seen the blocks in any other language. The concept seems beautiful, but completely unrelated to anything I know about programming.

The concept of blocks is logical and intuitive, but most likely very different from the way you experienced programming. Blocks are like alien logic – something so basic, that it changes the meaning of everything. Think of how an amphibian race of super-intellectual beings would differ from humans – this is how different the blocks concept is from your PHP functions.

As blocks are the basic structures of Ruby, chances are you have already seen them and did not really understand what was going on. I hope this post will be able to help you out with getting the hang of the concept really quickly.

So let’s start with an easy example. Run irb (cmd irb.bat) and define the method:

def aliens
i = 1
j = 2
yield(i, j)
end

This method just assigns two variables and then passes those variables to the block. Now let’s call the block:

aliens { |x, y| puts x, y }

It works as follows: aliens method is called, with Ruby recognizing that this method has a block attached to it. Once the yield is encountered within the aliens, it is passed to the block together with any parameters in the brackets. As i and j are local variables, we need to define the first and second variable to be used to hold i and j values. Finally we have the Ruby code that does something with those parameters. Puts just displays the values of i and j on screen. But you can do something more complicated:

aliens { |x, y| puts x+y*y }

This should display 5.

If you are not confused at this moment, great – you have almost mastered the blocks ;). If you are, think about the aliens as a function that allows three parameters – x, y and some arbitrarily complex Ruby code. Yield is the place where this code is executed. To make sure that this is the case, try this: (copy the code, save it to blocks.rb in your project directory and run ruby blocks.rb)

def aliens
i = 1
j = 2
yield(i, j)
i = “magick”
return nil
end

aliens { |x, y| puts x }

The script should print “1”. This is easy stuff. (Pedantic note. You can ignore “return nil“, it is there because Ruby returns the last value in the function (=method) as the result of the function, so if you run the code above in irb without “return nil”, you will see that aliens actually returns “magick”)

Another cool feature is the ability to test whether the method has a block. Check out this code:

def aliens
if block_given?
  i = 1
  j = 2
  yield(i, j)
 else puts “magick”
 end
end

aliens { |x, y| puts x }
aliens

In that case if the block is provided to the method, we execute the if statement, otherwise we execute the else statement. So, as a result the script should print “1” and “magick”.

How cool is that? 🙂

Updated in 2009:

Now that you know how blocks work, I would like to give you some implications for working with them in Ruby and Rails:

1 – It’s up to a method (or to method’s author) to have or not have a support for a block. If in the code above for method aliens there was no yield method, the block would just be ignored. If however, the yield is there and blockgiven? is not checked, you will receive an error – no block given on yield. A block is not a feature that you can use for any method any time with any parameters you can imagine. If a programmer thought of such a use for a block, you will have it, if he didn’t – you’re out of luck.

2 – It is up to the caller to understand what sort of blocks can be attached to a method. In the aliens example above, if you would try and call aliens { |x, y, z| puts x, y, z }, you will get the first two variables and nil for the third, and there will be no warning that you tried to get a variable (z), that is not really being passed (BUT – if you would try the other way round by having a block with only one variable x, Ruby will warn you and assign the merged value to a single variable x).

Also, consider an example when the information yielded is not really interchangeable. Let’s say that from my method I do an yield(x,y,zoom) for drawing a map. In my block I need to understand the correct sequence of variables in the yield and assign them correctly in my block. The only way to understand it is by looking up a documentation for this method, or sometimes more brutally – by going into the code and looking at the yield call.

Summary

So, what does this mean? This means, that blocks and yields are not magical, although they might seem so.It also means that sometimes in Rails it is very hard to understand which methods will accept a block and for those that accept the block what is the information passed to the block. However, usually there are no more than 2 variables being passed to a block, and you get used to working with the methods that way.

Hope it helps 😉

January 20, 2006 at 1:00 am 25 comments

Another good introduction article from Curt Hibbs

Curt Hibbs’ tutorials are the only accessible tutorials that I’ve read on Ruby on Rails. Curt has also written a great introductory article on Rails which you can find here.

January 16, 2006 at 7:51 pm 4 comments

Newbies beware!

So, I am trying to get deeper in the understanding of Ruby and Rails and things are progressing nicely. However, I have to say – the information on Rails and Ruby is not up to notch. Unless you are a seasoned programmer or a smart hacker, chances are you will be lost when trying to understand how to use the Rails API or what exactly you are supposed to do after you have installed Ruby on Rails and did an ONLamp tutorial. A good sentiment that every newbie will recognize instantly is expressed here.

January 16, 2006 at 7:48 pm Leave a comment

TextMate v1.5 released

TextMate by the look of it is a great editor for Ruby developers. New version was released just recently, but there are still no plans to release a PC version – only Mac users need to celebrate.

January 10, 2006 at 9:13 pm 1 comment

Ruby on Rails Cheatsheet

Blaine Kendall released a very nice 14-page PDF that summarizes nicely gotchas, syntax and some basic building blocks of both Ruby and Rails. Get the pdf from his blog post here.

January 10, 2006 at 9:01 pm 1 comment

Installing Rails on Windows (step-by-step tutorial)

20 July 09 Note – The new version of the Rails Windows installation guide is there. And the great news is that I even did it on the Rails v.2.3.3, released today! Please follow the instructions in this new guide, they are the most up to date ones!

28 June 09 Note – If you are new to Ruby / Rails, you should also get yourself acquainted with the Ruby syntax here.

Ok, so this will basically be somewhat a repeat of the information made by Curt Hibbs in this great hands-on tutorial. However, the versions of all products changed from the time Curt made his tutorial, and in some areas I felt that additional description was required. So, in this tutorial you’ll get a step-by-step instructions on installing Rails on Windows 2000 Server (Windows XP would be very similar).

(more…)

January 9, 2006 at 9:33 pm 207 comments

Do you need instant rails?

I have written about the Instantrails package before, but having tried it for a day, I decided to go with a proper installation. The reason for this is that I’ve never used to run either MySQL or Apache on my local computer, and as I have all sorts of firewalls and quirks on my computer, when things went wrong, I did not understand how I could fix them. Instantrails does not have any real documentation and I was not sure what exactly went wrong.

Also, Instantrails comes with phpmyadmin for MySQL admin, and for this it also needs to install php, which I thought was excessive – I’d rather go with my old trusted MySQL Control Center or the new Query Browser. So, if you are not a power user of either MySQL or Apache, I would recommend against using InstantRails.

Finally, for development you do not need to install Apache, as Rails comes with WEBrick, which should do the job good enough.

January 8, 2006 at 4:41 pm 1 comment

Great way to start with Ruby

Yes, books…

** UPDATED – November, 2009 **

1 – I have purchased the Programming Ruby 1.9 book from Pragmatic Programmers, and this is an excellent book that guides you through Ruby from the very beginning (you do not even need to know what classes and methods are) to the very end (which is a long section describing methods). I recommend everyone to purchase it, because before you know Ruby on Rails, it helps a LOT to know Ruby. It’s as simple as that.

2 – After that, the best book on Ruby on Rails is the Agile Web Development with Rails (3rd edition) book. I have actually read this one from start to finish and found it the most useful resource. You should definitely get the 3rd edition that came out in March 2009 and covers many new things in Rails.

3 – A good, concise guide on Ruby is The Ruby Programming Guide, co-written by the author of Ruby himself – Yukihiro Matsumoto. It goes into details of Ruby syntax and shows you the differences between Ruby 1.8 and 1.9. If you’re a programmer with experience, you should opt for this one.

4 – Another very good book that you could just read from cover to cover is The Rails Way. It’s not as up to date as the Agile Web Development book, but some of the things there are more and better explained, so it’s a good backup option – it definitely was for me! If you are a beginner Rails programmer, but have some experience in programming – this is a very good book.

5 – Finally, this book helped me with my mashup projects, as it explains to you how you could use Google Maps, Flickr, Yahoo, etc. – Ruby on Rails Web Mashup Projects. It provides you some ready code to copy&paste into your project.

If you have any more books you found useful – add them in the comments.

January 6, 2006 at 9:21 pm 3 comments

Ruby Magick

Today I have a much better grasp of Rails and the magick seems to fade away. And this is great. Rails generates a lot of excitement at the moment, and excitement leads to hype, when people who try to play the “magick” card, attributing it with “human-like” behaviour and popularizing a perception that Rails does everything for you.

The screencaps might be impressive, but frankly with right PHP libraries you would be able to get the same results just as easily. The best presentation on Rails is here, it was done way before all the Rails hype started (you can even see that there are about 20-30 people in the room). It is a bit long (2 hors!), but David (the Rails author) answers most of the questions – what made him move from PHP to Ruby, what MVC methodology means in Rails, and also codes an example, which just does not

And this brings me to a point – you should not expect Rails to be easy, you should expect to get into it first.

Also, I am not sure I like the thing about plural / singular (in Rails you enter it in singular, like “Book” when you name an object, and in database you have a table called “books”, because you see, it is a collection of book, the objects. And Rails goes one way further – mouse become “mice”, and so on. I am not sure that this is that useful for programmers, you could just as well have Book the object and Book the database table name. But I guess thisk quirky feature is something to put you in the mood for starting thinking about the object/database relationship, and it’s also a great soundbyte.

In the video presentation I mentioned, somebody asked a good question – “can Ruby be considered to develop a Bank System?” And this is a good question – for people to start looking into Ruby means a great amount of investment. If the language is not a proven concept or if the support is lacking, Rails can become just another fluke – an overhyped technology. And the answer to this would be that nobody knows yet – the critical mass of Ruby programmers is not there yet, so anything can happen. Ruby (and Rails) can become the next Linux or Apache – an industry standard robust technology with commercially available support. It can become an object-oriented PHP alternative. Or it can become Coldfusion – taking up a relatively small niche.

From what I saw in the last couple of days, both Ruby and Rails have a lot of potential. One thing Rails should be very good for is for rapid development of mini projects (3-4 people for 1-3 months). But mini does not mean bad – the flagship Rails project is a good looking project collab tool Basecamp. One of the best features that will be great for Web 2.0 start-ups and fans is the built-in support for Ajax in Rails.

I am still not sure about the learning curve for Ruby and Rails – if the time investment is not serious, even if the future of Rails and Ruby is not certain, you still will not waste it – learning about Ajax, Object Oriented Programming and Model-View-Controller methodology will not go unnoticed.

January 5, 2006 at 12:11 pm 6 comments

Model-View-Controller in PHP

Actually, if you are not interested in Ruby and want to try out MVC framework in PHP, you can check out these projects: Zoop Framework or a Rails clone: PHP on Trax.

January 4, 2006 at 8:13 pm Leave a comment

Older Posts


Starting to learn Rails?

Kindle

Get Kindle - the best e-book reader, that I personally use, and the only one that you can read on the beach - very useful: Kindle Wireless Reading Device (6" Display, Global Wireless, Latest Generation)