Thuta Learning
Ruby
BasicProgrammingBeginner

What is Ruby?

RubyLesson 220 min

What you'll walk away with

  • Explain who created Ruby and the design goal behind it: programmer happiness
  • Show that numbers, strings, symbols and nil are all objects by calling methods on them and asking for their .class
  • Explain the difference between a Ruby file and the interpreter that runs it, and why opening a .rb file in a browser shows no output
  • Name the main places Ruby is used: web apps (Rails), scripts and tools, and tests

Explain it simply

What Ruby is, simply

Ruby was created by Yukihiro "Matz" Matsumoto in the 1990s. His main idea was that writing code should be enjoyable for the developer, which is why Ruby syntax is simple and often reads like an English sentence.

The feature that most separates Ruby from other languages is that every value is an object. Numbers, strings and arrays all have methods of their own, so you can write 5.next or "ruby".upcase and call them directly. Think of each value as a small robot that you can send messages to: tell a number next and it answers with the following number, tell a string upcase and it answers with capital letters.

Problem → Why → Solution

The problem: Ruby does not know length("ruby")

If you learned C, Python or JavaScript first, you probably think of operations as functions you call on a value: len(text), Math.abs(x), parseInt(s). In Ruby the same operations are methods that belong to the value itself, so writing them the old way fails with an error such as undefined method 'length' for main (NoMethodError). The message looks confusing at first: what is main?

main is the top-level object that every Ruby script runs inside. When you write length("ruby") without a receiver, Ruby tries to call length on main, and main has no such method. The string "ruby" does have a length method, but you only get it by asking the string itself.

wrong_style.rb
# Written the way a C or Python programmer might think
puts length("ruby")     # NoMethodError: undefined method 'length' for main
puts upcase("ruby")     # NoMethodError: undefined method 'upcase' for main
puts abs(-5)            # NoMethodError: undefined method 'abs' for main

Why Ruby works this way

Putting behaviour on objects keeps related things together: everything a String can do is listed under String, and tools such as irb can show you that list. You learn one rule, value.method, instead of memorising a pile of unrelated global functions.

Core concept: sending messages to objects

In Ruby every value is an object, and every object belongs to a class. The class decides which methods the object understands: Integer defines next and times, String defines upcase and length, NilClass defines to_a and nil?. You use a method by writing the object, a dot and the method name, which Ruby describes as sending the object a message. That uniform shape is why Ruby needs far fewer special functions than languages with primitive types: there is no global length(x), because length belongs to the things that have a length.

You can always ask an object about itself. .class returns its class, .respond_to?(:name) says whether it understands a message, and .inspect gives a text form meant for developers. Even a class is an object: 5.class is Integer, and Integer.class is Class. Integer inherits from Numeric, which is why 5.is_a?(Numeric) is true, and almost everything inherits from Object.

What you writeWhat Ruby does
5.nextSends next to the Integer object 5 and gets 6
"ruby".upcaseSends upcase to a String and gets a new String, "RUBY"
nil.to_aSends to_a to nil, which answers with an empty array []
5.respond_to?(:upcase)Asks whether the Integer 5 understands upcase; the answer is false

Ruby is also interpreted: a program called ruby reads your .rb file and carries it out. Opening the file in a browser, or double-clicking it, only shows or edits the text, because a browser has no Ruby interpreter. Method lookup also happens while the program runs, not before. If you send a message that the object does not understand, Ruby raises NoMethodError at that moment, which is the cost of dynamic typing and is tied to the fact that you can add methods to your own classes at any time.

Mental model: send a message to an object
  1. Start from a value: 5, "ruby", nil
  2. Write a dot and a method name after it
  3. Its class supplies the method
  4. The method returns a new value

Ruby has no loose functions like length(x); behaviour lives on the objects.

General pattern: calling a method

ruby
receiver.method_name
receiver.method_name(argument)
receiver.method_name(argument) { |item| block_body }

The receiver is the object on the left of the dot. A method name follows, then optional arguments in parentheses, then an optional block in braces. The same shape works for every object, whether it is a number, a string or something you define yourself.

Example: sending messages to objects

This program sends messages to objects of different kinds and looks at what they answer. It is under ten lines long but says a lot. Predict the output before you run it, especially the last three lines.

objects.rb
# Everything in Ruby is an object, even numbers.
puts "Hello, Ruby!"
puts 1.next
puts "ruby".upcase
puts 5.class
puts nil.class
puts 5.class.class
puts 5.respond_to?(:times)
puts 5.respond_to?(:upcase)

Code breakdown

  1. A number receives a messageputs 1.next

    1 is an Integer object, so you can send it next directly. The answer is the following number, 2, and puts prints it.

  2. A string receives a messageputs "ruby".upcase

    upcase returns a new String in capitals. The original "ruby" is left alone; the version that changes it in place is called upcase!.

  3. Asking for the classputs 5.class

    .class returns the object's class. puts prints the class's name, so you see Integer.

  4. Even nothing is an objectputs nil.class

    nil is the value that stands for "no value". It is an object too, of class NilClass, which is why methods such as nil.to_a work.

  5. Classes are objectsputs 5.class.class

    5.class is Integer, and asking Integer for its own .class gives Class. In other words, classes are objects too.

  6. Asking what an object understandsputs 5.respond_to?(:times)

    respond_to? asks whether the object understands a message. 5 understands times, so the answer is true, but it does not understand upcase, so that one is false. The ? is part of the name; methods that answer true or false are conventionally named this way.

You should see
Hello, Ruby!
2
RUBY
Integer
NilClass
Class
true
false

The path from file to output

Between a text file and the words on your screen sits the interpreter. The picture below shows the path of a one-line program; a browser appears nowhere on it.

text
From hello.rb to the terminal
-----------------------------
 hello.rb            ruby (interpreter)            terminal
+-----------+       +---------------------+       +--------------+
| puts "Hi" | ----> | read, check, run    | ----> | Hi           |
+-----------+       +---------------------+       +--------------+
 plain text          installed on your PC          standard output
bash
cd path/to/your/folder
ruby hello.rb

Ruby implementations and versions

"Ruby" names the language, and several programs implement it. Every sample in this course runs on CRuby, the implementation behind the ruby command. A Ruby version is a major.minor.patch number, and the output quoted here comes from Ruby 4.0.9. Check the official release notes to see what changed between versions.

ImplementationWhat it is
CRubyThe reference implementation that the ruby command usually means, written mostly in C
JRubyRuby running on the Java Virtual Machine, able to use Java libraries
TruffleRubyA Ruby implementation built on GraalVM

In real projects

Where Ruby shows up in real projects

Ruby turns up in many places. On the web, the Rails framework powers sites such as GitHub and Shopify. Among tools, the Homebrew package manager and the Jekyll site generator are written in Ruby. For testing, RSpec and Minitest are widely used by Ruby teams.

The "every value is an object" idea shows up in all of them. Readable lines such as Rails's 3.days.ago, Minitest assertions and method chains inside your own classes are possible only because even plain numbers and strings can receive method calls. Understanding this idea early makes many later lessons easier.

A practical habit comes out of it: when something behaves strangely, ask the object. In a real codebase you will often write value.class or value.inspect during a debugging session to find out what you are actually holding, because the answer is frequently nil.

Common mistakes

Common beginner mistakes

1. Opening the file instead of running it

Double-clicking hello.rb or dragging it into a browser shows nothing useful, because only the ruby interpreter understands the code. Open a terminal in the folder that holds the file and type ruby hello.rb.

2. Calling methods in function style

Writing length("ruby") or upcase(name) raises undefined method 'length' for main (NoMethodError). Write the value first and chain the method with a dot: "ruby".length. The for main in the error means that no receiver was given, so Ruby looked on main.

3. Sending a message the class does not know

5.upcase gives undefined method 'upcase' for an instance of Integer, and nil.upcase gives undefined method 'upcase' for nil. The error names the receiver's class, so first check that the object you hold is the one you think it is. In practice it is most often an unexpected nil.

Best practices

Best practices

  • Reach for .class and .inspect first when you do not know what a value is; the answer often differs from what you assumed.
  • When you are unsure whether a method exists, ask with respond_to? or try it directly in irb.
  • Read a trailing ? or ! in a method name as meaningful: ? usually means it answers true or false, and ! usually means it changes the value in place.

Mini challenge

Mini challenge: a type inspector

Write a describe method that takes a value and returns text such as 42 -> Integer, and a can_do method that answers yes or no depending on whether an object understands a message. Then call them on values of several kinds and print the results.

  • describe(value) returns text of the form "42 -> Integer" using value.inspect and value.class
  • can_do(value, message) returns "yes" or "no" using respond_to?
  • Print describe for 42, "hello", 3.5, nil, :ruby and [1, 2]
  • Print can_do for (5, :times), ("5", :times) and (nil, :to_a), and predict the output before running
inspector.rb
# inspector.rb
def describe(value)
  # TODO: return text like "42 -> Integer" using inspect and class
end

def can_do(value, message)
  # TODO: return "yes" if the object responds to message, otherwise "no"
end

# TODO: print describe(...) for six values and can_do(...) for three pairs

Expected: Six lines for describe, then three for can_do: 42 -> Integer "hello" -> String 3.5 -> Float nil -> NilClass :ruby -> Symbol [1, 2] -> Array yes no yes

Show hint

inspect shows a string with its quotes, so "hello".inspect is "hello" with the quote marks and nil.inspect is nil. For yes or no use a ternary: value.respond_to?(message) ? "yes" : "no". Pass the message as a symbol such as :times.

Show solution
inspector.rb
def describe(value)
  "#{value.inspect} -> #{value.class}"
end

def can_do(value, message)
  value.respond_to?(message) ? "yes" : "no"
end

puts describe(42)
puts describe("hello")
puts describe(3.5)
puts describe(nil)
puts describe(:ruby)
puts describe([1, 2])
puts can_do(5, :times)
puts can_do("5", :times)
puts can_do(nil, :to_a)

Quick quiz 1 / 3

What does puts 5.class.class print?

Quick quiz 2 / 3

Which of these raises NoMethodError?

Quick quiz 3 / 3

Why does ruby hello.rb produce output while opening hello.rb in a browser does not?

What to remember

  • Ruby was created by Matz and designed so that developers enjoy writing it
  • Every value is an object that you send messages to with object.method, and you can ask it questions with .class and respond_to?
  • A Ruby file is run by the ruby interpreter; opening it in a browser does not run it
  • NoMethodError names the receiver's class, so check which object you are really holding

Ruby 4.0 Release — Ruby

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

What is Ruby? | Thuta Learning