What Ruby Is
Imagine you run a small coffee cart called Bean Cart, and you want a script that totals the day's sales. In some languages that takes a page of ceremony. In Ruby it reads almost like a sentence. That is the whole point of the language, and it explains most of the choices you will meet in this course.
The rule
Ruby is built for people first: everything is an object.
Ruby was created in Japan by Yukihiro Matsumoto ("Matz") and first released in 1995. His stated goal was to make programmers happy, so the language favours code that is short, readable and pleasant to write over code that is easy for the machine.
"Everything is an object" is the idea that holds it together. A number, a piece of text, even "nothing" (nil) is an object you can ask questions of:
5.class # => Integer
"latte".upcase # => "LATTE"
nil.class # => NilClass
3.times { puts "Order up!" }That last line is not special syntax. 3 is an Integer object, and times is a method it understands. Once you see that pattern, a lot of Ruby stops looking like magic.
A few more facts worth holding on to:
- Interpreted. You run a file with
ruby sales.rb; there is no separate compile step you manage yourself. The main implementation is called CRuby (or MRI), and modern Ruby 3.x ships with a just-in-time compiler, YJIT, that speeds up long-running programs. - Dynamically typed. A variable does not declare a type; the object it points to carries its type.
- Interactive. Type
irbin a terminal and you get a prompt where each line runs as soon as you press Enter. - Famous for Rails. The Ruby on Rails web framework made Ruby popular, but Ruby is a general-purpose language used for scripts, tools and automation too.
The shortcut
When a Ruby line puzzles you, read it as object, dot, message. The thing on the left is an object; the word after the dot is a request you are sending it; anything after that is extra detail for the request.
Find the first object
"bean cart"is a String object.
The common mistake is to hunt for keywords and built-in functions the way you might in another language. In Ruby, most of the work is done by methods that belong to objects, so ask "what object is this, and what can it do?"
Drills
Answer fast — trust the rule.
What does 5.class return in Ruby?
In 3.times { puts "Order up!" }, what is times?
Which command gives you an interactive Ruby prompt?
What was Matz's main design goal for Ruby?
Remember
- Ruby is built for people first, and everything in it is an object.
- Read any line as object, dot, message, from left to right.
- Trap: looking for built-in functions; in Ruby the behaviour usually lives on the object.
