Intro to Ruby
Ruby is a very flexible language that gives the programmer a lot of power. Ruby is focused on programmer productivity over machine optimization. This tutorial will demonstrate the syntax of ruby with short code examples.
Ruby comments are marked with
#. The example code in this tutorial will often show output marked with a
# This is a comment #=> Output will be shown like this 1+1 #=> 2
Ruby has the following characteristics:
Everything is an Object
Unlike Java, absolutely everything in Ruby is an object. Even a literal number (like
3) is an object with methods. For example:
3.to_s #=> "3" 3.class #=> Fixnum
See Classes and Objects II for more. Coming soon!
The ruby core language and standard library come with a large number of useful methods. For example, to reverse a string in ruby, you can just do:
"hello".reverse #=> "olleh"
Blocks of code for passing
Ruby is really into passing around blocks of code. See Blocks for more info.
Variables in ruby can switch between holding different types, such as integers, strings or anything else:
thing = 5 #=> 5 thing = "hello" #=> "hello" thing = true #=> true
In Ruby, methods can be called on objects without checking what type they are. As long as they have that method, the code will work.
Very Dynamic - Edit any class or method anywhere
Ruby allows classes and methods to be edited at any point even while running code.
Ruby was released in 1995, but became popular a decade later with the release of Ruby on Rails, a web app framework written in Ruby.
Try Out Ruby
To try out Ruby on your computer, you can use IRB, the Interactive Ruby Shell. This evaluates code every time you hit enter, so it's useful for exploring how Ruby code works. Ruby and IRB come installed on Mac, so just open up your terminal and enter
irb. On Windows, you can use the RubyInstaller. Don't want to download anything? You can try out Ruby online.
If you know other programming languages and want to know how Ruby compares, see the official Ruby From Other Languages. To get familiar with Ruby by looking at example code, see Learn Ruby by Example. This module will cover the same material with a little more explanation.