Getting Started With Ruby On Rails

Advertisement

If you’re a Web developer who’s been curious about Ruby on Rails but has never gotten around to trying it out because you couldn’t find a suitable overview of its advantages, then this article is for you.

We want to bring Ruby on Rails closer to those who want to take a peek first, without going through an entire tutorial. So, this article is structured a little different from most other introductions out there; hopefully it is more useful because of this.

I assume you’re already familiar with some other form of Web development, whether PHP, Python, Perl or Java, and relational databases like MySQL. First, we’ll introduce Rails and Ruby and the basic ideas behind both. I’ll teach you just enough Ruby so that you understand the code samples. I’ll tell you how to get Ruby on Rails running on your computer, and I’ll give you an overview of the basic functionality of Rails and demonstrate how Rails’ main parts work together.

This tutorial consists of two articles: in the current, first article we get started with some basic concepts and essential components of Ruby on Rails. In the second part (it will be published next week) you will learn how to install the engine; you’ll also take a closer look at Rails’ inner workings and discover main advantages of Ruby on Rails. Please stay tuned.

After reading these parts, you should have an idea of whether Rails is for you. If you get the feeling that it is, I’ll point you to some good tutorials on the Web that you can use to learn Rails. I’ll also provide a lot of further reading recommendations so you can dig as deep into the topic as you like.

I’m taking this approach because Rails is almost 5 years old now and has become very complex. There are a lot of “Create-your-own-blog-in-5-minutes”-type tutorials out there already, and rather than adding another one, I wanted to provide this kind of rough overview to help you decide whether to take this adventure.

You may want to take a look at the following related posts:

The Idea Behind Rails

Ruby on Rails was created by David Heinemeier Hansson as a kind of byproduct of Basecamp’s development at 37signals in 2004. Basecamp was built in Ruby because Hansson found PHP and Java not powerful or flexible enough. It was quite an obscure language back then, without the large eco-system available today. To make development easier, Hansson rolled his own Web development framework, based on simple ideas that had proven successful elsewhere. Rails is founded on pragmatism and established paradigms instead of exotic new ideas. And that’s what made it so successful.

Rails is based on the Model-View-Controller pattern that splits your application into three parts:

  • The Models are your business objects describing the structure and behavior of the problem your application is trying to solve. These are usually backed by an Object-Relational-Mapping framework that persists your objects to a database in the background.
  • The Views are the templates that render data to the user and all the logic surrounding presentational aspects of your app.
  • The Controller sits at the heart of everything, processing requests from clients, initiating changes in the models and triggering the rendering of the templates.

Rails is “opinionated software.” It doesn’t want to be everything for everyone. It focuses on one way of doing things and streamlines all its parts around that way. That’s not to say there’s no possibility of doing things differently if you need to, but you’ll definitely have it easier if you do things “the Rails way.” And that way happened to be exactly the right one not only for Hansson but for a lot of other developers, too, another important reason for Rails’ success.

Programmer productivity was the main goal during Rails’ development, not performance. This has led to a lot of controversy and claims that arise over and over about how Rails can’t scale. This is Rails’ own fault to a certain degree. In its early days, it had the image of a Web development framework messiah of hope and wonder that would lead us all to the promised land were applications wrote themselves. The Rails team didn’t do enough to keep expectations more realistic, and some people became disappointed.

While it’s true that Ruby on Rails is slower than comparable stacks on PHP or Python, it certainly does scale, as hundreds of successful deployments are proving. You’ll just need to scale sooner and put some thought into it. Remember also that Ruby’s current default implementation is terribly inefficient, but alternatives are on the way. There’s nothing inherently slow about the language, though, as blazing-fast implementations of Smalltalk (a language very similar to Ruby) prove. Ruby will only get faster. As the saying goes, you don’t have a performance problem until you have a performance problem, and all this talk should not scare you yet. You haven’t even started. ;)

Now, before I introduce you to the framework, let’s get started with Ruby.

A Gem From Japan

Ruby on Rails owes not only half its name but its entire feel and flexibility to “Ruby,” that neat little language from Japan.

Ruby came out in 1995 and was developed by Yukihiro Matsumoto, or “Matz” as he’s called in the community. Version 1.0 was released in 1999 and slowly gained recognition in the west from then on.

A key point in the spread of Ruby was the release of “Programming Ruby,” also called the “Pickaxe” (a reference to its cover illustration), by the Pragmatic Programmers. “Programming Ruby” was the first comprehensive English guide to the language and API.

Ruby was designed with simple principles in mind. Matz took the most successful and powerful elements from his favorite programming languages — Perl, Smalltak and Lisp — and combined them into one language with easy syntax. One goal was to make Ruby feel “natural, not simple” and to create a language “that was more powerful than Perl, and more object-oriented than Python.” This results in Ruby’s core principle: Everything is an object.

Objects

Let’s stop here and examine this. Really, everything is an object in Ruby. True and false are objects, literals are objects, classes are objects. You can call a method on a numeric literal:

>> 5.next
=> 6

Operators in Ruby are nothing but methods:

>> 5 * 10
=> 50
>> 5.*(10)  # times-operator called as a method (dot-notation)
=> 50       # with a parameter (in parentheses)

Ruby is extremely flexible and open. Almost everything about it can be changed or manipulated at runtime:

  • You can add and remove methods and variables to and from objects.
  • You can add and remove methods and variables to and from classes.
  • You can truly manipulate any class this way, even core classes like String and Integer!

Here’s an example:

>> "hi".repeat(4)
NoMethodError: undefined method `repeat' for "hi":String
>> class String     # Open the string class and add the method
>>   def repeat(i)
>>     self * i
>>   end
>> end
=> nil
>> "hi".repeat(4)   # Call it again on a fresh String literal
=> "hihihihi"       # And there it is!

Here, I defined the method repeat on the String core class, and it was immediately available on a string literal.

And he who giveth, taketh away:

>> class String             # Open up the method again
>>   undef_method :repeat   # And remove the method
>> end
=> String
>> "hi".repeat(4)           # Try to call it
NoMethodError: undefined method `repeat' for "hi":String

I could have also done this with predefined methods. They are no more “special” than the methods we have defined.

Let’s review the definition of repeat in the above example for some more interesting tidbits. Note that we’re not saying return anywhere in the body. That is because in Ruby, methods always implicitly return the value of their last expression. You could of course always jump out of a method by using return before reaching the last statement, but you don’t have to. The expression we’re returning is self * i. Self is equal to this in Java and $this in PHP and always refers to the current object. The times-operator on a string repeats the string as often as told by the second operand/parameter, i in this case.

Loops

You rarely see manual iterations in Ruby, like for or while loops. Instead, Collections come with their own iterators that you can pass blocks to, which are executed for every element in the collection:

a = "Hey "
[1, 2, 3].each do |num|
    puts a * num
end

# Outputs:
# Hey
# Hey Hey
# Hey Hey Hey

What you see here is an array literal containing numbers. On that array, the each method is called, an iterator that takes a block and calls the block for every element in the array. The block starts with the do, followed by a list of its parameters enclosed in pipe symbols. Here we have one parameter called num that will take on the value of the array element in each iteration. Inside the block, we’re simply outputting the result of a * num. The definition of * on Strings is to repeat the string accordingly. We could have put the String inside the Block, but I wanted to demonstrate that blocks have access to their surrounding scope.

Syntax

Ruby likes to keep the syntax clean and friendly. You can see this in the above examples. Although heavily influenced by Perl, Ruby doesn’t have Perl’s excessive use of special characters. You can use semicolons to end lines, but you don’t have to (and no Ruby programmer does). You don’t need to surround method parameters with braces in unambiguous situations (although it is recommended you do so if they enhance readability), and you especially don’t need to provide empty braces around an empty parameter list. That’s what makes accessors look so much like native properties.

Blocks are framed by do and end. You should only use equivalent curly braces if your blocks don’t span several lines. The only significant use of special characters is found at variable declaration. Variables in Ruby are prefixed with special characters to indicate their scope. Variables starting with a lowercase letter are local variables. Variables starting with an uppercase letter are constants. (This means that all classes are constants, too, since classes start with uppercase letters.) Instance variables start with an @. Class variables that are shared among all instances of a class start with @@. Finally, global variables all start with a $.

You’ll often find methods ending in ? or !. These are not special characters. It is merely conventional in Ruby to use question marks for methods that query an object for a Boolean condition, like Array#empty?, or exclamation marks for methods that are destructible:

>> a = [5, 1, 9, 2, 7]   # Create an array and store it in a
=> [5, 1, 9, 2, 7]
>> a.sort                # sort merely returns a new, sorted array
=> [1, 2, 5, 7, 9]
>> a
=> [5, 1, 9, 2, 7]       # a still is in its original order
>> a.sort!               # sort! instead sorts the original array
=> [1, 2, 5, 7, 9]
>> a
=> [1, 2, 5, 7, 9]       # a was changed

Conditionals

Conditionals in Ruby are very similar to other programming languages, with two notable exceptions. First, it’s possible to put a conditional after the statement it protects to make the code more readable:

execute_dangerous_operation() if user.is_authorized?

# is equal to

if user.is_authorized?
  execute_dangerous_operation()
end

Secondly, Ruby has not only an if but an unless. This is a syntactic nicety for when you want to check for the absence of a condition in a more readable manner:

unless user.is_admin?
  user.delete
else
  raise "Can't delete admins"
end

Symbols

Sometimes you’ll see names starting with a : (colon). These are a very special feature of Ruby called symbols. Symbols can be used to index hashes or mark states in a variable like you would with an ENUM in C. They are very similar to Strings but also very different. The point about symbols is that they don’t really occupy space in memory, and the same symbol literal always resolves to the exact same symbol:

>> "a".object_id  # object_id returns Ruby's internal identifier for an object
=> 3477510
>> "a".object_id
=> 3475550        # a new object on the heap
>> :a.object_id
=> 184178
>> :a.object_id
=> 184178         # the same literal refers to the exact same Symbol object

You’ll find them very often as parameters to methods, where they indicate how a method should work,

User.find(:all)   #find all users
User.find(:first) #find the first user

or as pointers to methods and variables (see the undef_method example in the “Objects” paragraph above).

Classes and Modules

Ruby supports single inheritance only, but for added flexibility it supports a feature called Mixins. In Ruby, it’s possible to define Modules that contain Methods and constants and to include these modules in a class via the include method. This way, you can extend the functionality of a class very easily.

Many of Ruby’s core classes even use this mechanism.Array and Hash, for example, both include the Enumerable module to provide a lot of convenience methods for iterating over their contents.

Often, Modules pose certain requirements to classes that include them. The Enumerable Module, for example, requires classes to provide at least an each method and an implementation of <=>, too, if its sorting features are to be used.

Modules also serve other purposes. Most importantly, they can be used to organize code into namespaces. Because classes are constants (which means you can’t assign another class to the same name), they can be stored in modules. These modules can then be nested to form namespaces.

These paragraphs probably won’t enable you to write Ruby programs, but you should be able to understand the code samples in this article now. If you want to explore Ruby a little, try the great interactive tutorial at Try Ruby, or take a peek at one of the books listed at the end of this article. If you just want to see some more code samples, check out the Wikipedia page on Ruby.

In the second part of this tutorial we will get rolling with Ruby on Rails, install the engine, take a closer look at Rails’ inner workings and discover main advantages of Ruby on Rails. Please stay tuned.

(al)

↑ Back to top

Jan Varwig is a programming language enthusiast, currently writing his CS diploma thesis about server-side JavaScript, and a software developer with 10 years of experience working for 9elements and as an independent freelancer. His blog and CV can be found at jan.varwig.org.

  1. 1

    Serge Ovanesyan

    March 19, 2009 7:33 pm

    If you are learning Ruby, you have to read this guide.

    I just don`t know how you could have missed it in this article.

    -27
  2. 2

    WOW!

    I love all of the historical information provided here along with the code examples!
    Being a budding web developer I am only familiar with Ruby through passing conversation and envy. This definitely helps to clear some things up!

    OH!! DEFINITELY CHECK OUT #5 SERGE’S LINK

    -10
  3. 3

    Sean McCambridge

    March 19, 2009 6:53 pm

    Wow, y’all read my mind! Thanks for the kick in the ass. :) @mccambridge

    1
  4. 4

    Ruby on Rails is the future of the Internet
    thanks so much

    3
  5. 5

    ruby is gonna beet all other web languages

    0
  6. 6

    Great post! This looks like a very powerful and fun language, I’m eager to play with it!

    -1
  7. 7

    Awesome! Hopefully there will be more articles about ROR ;-)

    -1
  8. 8

    Still confused … very confused

    0
  9. 9

    It sounds quite nice, but I tried to install a working development enviroment for Ruby. After the tenth fail I stopped and threw it from my computer. Anyway, I think if you are on the point to decide which programming language you should learn, you can give Ruby a try. For me and my everyday business it would take too long to switch from php to ruby. But anyway, nice article!

    Cheers
    Dietmar

    1
  10. 10

    Always nice to raise awareness of Ruby/Rails. Thanks for posting.

    I would love to see an article on deploying rails apps, particularly on shared hosting (Dreamhost is my host).

    1
  11. 11

    Looks funny. But the hype is over!

    -4
  12. 12

    Hype is not over!
    The merge of Rails and Merb is creating a new hype and is certainly the best thing that could happen in a latest release. I see i bright future for Ruby as well as Rails…

    Kick ass philosophy behind!

    0
  13. 13

    biased article

    -2
  14. 14

    SM stick to the PHP&Ajax… :)

    -1
  15. 15

    I already tried it… And really it’s not worth it as soon as you want perf, and custo!
    There are few modules useful but that’s really it.
    You can search here for some of my works on it.

    -2
  16. 16

    Still confused too!

    0
  17. 17

    @Serge Ovanesyan

    You’ll find the recommended resources in part 2 of the article.
    I deliberately left out Why’s poignant Guide. While it’s pretty entertaining and nice for beginners to programming, I don’t think it’s the best source of learning for developers coming from other languages who want to get up to speed quickly. Also, the Poignant Guide is a little outdated by now.

    0
  18. 18

    I am looking forward for next week second part :)
    there is a spelling mistake in the image of MVC scheme: the controller is repsonsible for the control….

    1
  19. 19

    jan, great article!! Looking forward for the second part!

    -1
  20. 20

    Good job!
    There should be more overviews like this over the internet

    -1
  21. 21

    Serge Ovanesyan

    March 20, 2009 4:13 am

    @Jan Varwig

    Thanks for the reply.
    I still think Why`s Guide is too much fun to miss, though. gj

    -1
  22. 22

    Have you ever actually benchmarked Rails against comparable PHP stacks ? You might wanna listen to Yehuda – http://www.merbcamp.com/video/katz3.mp4

    -1
  23. 23

    Great article!
    Was looking forward to read about Rails on SM.
    Rails is gonna merge with Merb so maybe a follow-up on this topic?
    Thanks SM! Go on with rails!

    -1
  24. 24

    so, how to implement it on web? i’d rather learning by example

    -1
  25. 25

    can’t wait to see the second article.
    Thanks a lot for this nice introduction.

    -1
  26. 26

    Nice post. I’ve been using Ruby, but need to start using Rails. This will help. Thanks.

    -1
  27. 27

    This is the clearest entry-level explanation I’ve yet read on the power of the Ruby language. Good job!

    0
  28. 28

    Great read. Looking forward to the 2nd part!

    0
  29. 29

    Jean-Philippe M.

    March 20, 2009 11:12 am

    Hi,

    there is a mistake in the unless exemple, where it’s actually used as an if in the code.

    Anyway thanks for this intro, although it could be indicated that the MVC design pattern wasn’t “invented” by the rails devs, and you should also talk about the DRY philosophy of rails/ruby.

    0
  30. 30

    I’m an avid PHP snob, but I got into Ruby on Rails for a bit last year. It really IS cool and gets you to program in good habits I still use to this day. Performance and difficulty of deploying live holds me back from getting too excited. If hosts were cooler about rails, I might consider it!

    Still really cool though.

    0
  31. 31

    @Jean-Philippe

    Could you explain where you think the mistake is?

    0
  32. 32

    Carsten Nielsen

    March 20, 2009 8:46 pm

    Deploying a Rails app does not have to be difficult. With Passenger, deploying a simple app on one sever can be as easy as PHP, just copy the files over and you’re good to go.

    DreamHost supports Passenger for commodity Rails hosting, I have my blog on there, all I have to do is pull from source control to a folder DreamHost and it’s live.

    @Jean-Philippe Rails is not about “owning” certain design principles, it’s about bringing them together in a way that’s useful for developing web applications. I think it’s implied, and pretty clear, that MVC was not “invented” by DHH.

    0
  33. 33

    I’m an avid PHP snob – Michael Kelley

    There goes today’s oxymoronic statement. PHP is a second-rate, hacked-together language; it encourages poor programming practices among other things. How you can be proud of that and look down your nose at other developers is a testament to your ignorance.

    -4
  34. 34

    Ahmed El.Hussaini

    March 20, 2009 10:01 pm

    I’m sorry to say this but I think this article is considered to be one of the weak articles I’ve read here at SM.

    0
  35. 35

    Feedweaver you new RSS reader

    March 20, 2009 11:52 pm

    Check out a new RSS reader for you at feedweaver.net

    -2
  36. 36

    Can’t wait for the second part!

    0
  37. 37

    so basically the Model is the Database, Controller is the Scripts, then View is the Template. :D

    2
  38. 38

    Jean-Philippe M.

    March 27, 2009 2:54 am

    @Jan Varwig : Sorry, I simply misread the code (in my head I was thinking about only admins having a right to delete users).

    0
  39. 39

    “more object-oriented than Python.” This results in Ruby’s core principle: Everything is an object.”

    Not to start a flame-war, but this sentence is just wrong. In python everything is an object too.

    0
  40. 40

    I’m confused too. It’s coding structure is horrible!

    0
  41. 41

    Stephen Costello

    March 30, 2009 1:47 am

    really interesting stuff, think I’ll take the jump and learn how to do develop in it.

    0
  42. 42

    I’m a clientside developer, so I rarely take my AJAX/Flash hat off. Previously though, when said hat was removed, I’d always resorted to PHP. Recently I’ve been playing about with Flex, and I’ve found that Rails is a fantastic choice for the data access layer. If you have any interested in Flex/Air apps, definitely give Ruby a look.

    This book is pretty fly: http://www.flexiblerails.com/

    0
  43. 43

    Thanks for helping de-mystify.

    0
  44. 44

    Nice posting, Explained clearly about Ruby.

    0
  45. 45

    Vladamier Vondouchkein

    May 31, 2009 3:09 am

    I NEED POOPIE

    -4
  46. 46

    My company switched to Rails from PHP last year… now after 12 months i can say that this switch was a god send! Rails and Ruby are a killer combo! We’ve drastically improved our efficency! I’m in love with it!

    0
  47. 47

    From what I have seen of Ruby, it is a fantastic language. Neat, clean, concise, non-verbose. Will it ever become a “real” language, and be able to be compiled under Windows and Linux?

    ROR looks great also.

    As I always say – time will tell.

    Thanks for a great article.

    Brian

    0
  48. 48

    It’s not true that everything is an object in Ruby, even though everyone keeps saying that. Some things are “syntax”. Please don’t misinform. :)

    0
  49. 49

    Ruby and Rails are gorgeous entities. As a long-time PHP programmer turned Rubyist, the elegance of the syntax and over power and organization of the language is stunning. I was so compelled by Ruby/Rails, in fact, that I started up a website to preach the good word and help people thrive in ruby/rails.

    0
  50. 50

    Great article.
    Ruby / Rails is really cool. Progressively since I started programming in the 1970′s I have come to realize that the essential missing attribute in almost all languages is “elegance”. Ruby has oodles of this rare commodity. In fact, not since I worked with Dick Pountain’s “Object Orientated Forth” in the 1980′s have I found anything remotely as elegant.

    0
  51. 51

    The hype is so over. RoR is so 2005. Learn a language that actually will get you a real job.

    -2
  52. 52

    Btw, is it just me or do most of these pro-Ruby posts sound like soundbites from a commercial? Soo lame….

    0
  53. 53

    This is a great description of what Ruby on Rails is. This covers everything from start to finish from the setup to the syntax. If you are looking to get started with RoR, check out the article at: http://topcweb.com/content/ruby-rails-setup

    0
  54. 54

    Nice to have such articles. It would be better if you describe a little about integrating ruby to the front end. I mean how it is integrated with html. (I don’t know if I make sense.)

    0
  55. 55

    I like how at the beginning of the article, ASP.Net and Microsoft MVC are omitted from the list of “other forms of web development.” You can flame this all you want, but .Net and its ASP.Net/MVC frameworks are amazing and very fast. The issue comes in ASP.Net allowing drag/drop development that is far from scalable. But, if you are a real web developer, understand client-side scripting, real AJAX, caching and how to build component-based applications, I would toss out the hate and check out ASP.Net. BTW, you can download the Express Web Developer for free, which are awesome tools. If you think RoR is the next coming of Jesus, there’s no helping you (you probably once thought that about Java and probably PHP before that). Carry on.

    0
  56. 56

    Great Tutorials for Ruby on Rails….i like this article…I dont know how to start learn ROR, this tutorial help me lot to learn ROR…..Thanx

    0
  57. 57

    really helpful i enjoyed this….. thank you for such a post

    1
  58. 58

    Nice posting…. explained clearly about RoR… good job Smashings…

    0
  59. 59

    Thanks for the good article. Made a lot of sense. Very clearly written.

    0
  60. 60

    Ruby is magnificent, switched from php to ruby last month and i am impressed……

    0
  61. 61

    I’d suggest putitng a URL where future versions may be found within the cheatsheet. Also, if you provided the source (input to PDF process) we could send you patches, (I spotted one typo: blogkcs ). It is probably sufficiently long to merit a table of contents.Seriously appreciated, please consider this as encouragement to develop it further.

    0
  62. 62

    itsssss………great… i cant explain……..thanxxxx sir

    0
  63. 63

    hi friend i don’t Ruby but now i am ready to learn ruby .can you help me??

    0

Leave a Comment

Yay! You've decided to leave a comment. That's fantastic! Please keep in mind that comments are moderated and rel="nofollow" is in use. So, please do not use a spammy keyword or a domain as your name, or else it will be deleted. Let's have a personal and meaningful conversation instead. Thanks for dropping by!

↑ Back to top