Skip to content
Tutorials Center
My learning

Topics

Lesson 6 of 134 ยท Getting Started

Basic Types

Tour Ruby's basic types - Integer, Float, String, Symbol, true, false and nil. Learn class, is_a?, truthiness, conversions and the errors that wrong types cause.

Ruby has no "primitive" types. Every value you write, from 42 to "hello" to nil, is an object: it knows its own class and has methods you can call. This is different from languages where numbers are special and strings are library types. In Ruby you can write 42.even? and nil.to_a with the same dot syntax you use everywhere else.

This lesson introduces the basic building blocks: Integer, Float, String, Symbol, true, false and nil. You will learn how to ask any value what it is, which values count as "true" in a condition (a rule different from many languages), how to convert between types, and what happens when types do not match. Later lessons treat numbers, strings and symbols in much more detail.

The tour

Ruby What is this value

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Each value reports its class with .class. Here are the basic ones:

  • Integer: whole numbers of any size (42, -7, 1_000_000). There is no overflow, because Ruby switches to big numbers automatically.
  • Float: decimal numbers (3.14, 2.5e-3), stored as 64-bit binary floating point.
  • String: text ("hello"), a sequence of characters you can change.
  • Symbol: a name (:ok), an immutable label that is the same object everywhere. See Symbols.
  • TrueClass and FalseClass: the two boolean values true and false. There is no Boolean class.
  • NilClass: the single value nil, meaning "nothing" or "no value".
  • Array, Hash, Range: collections that get their own lessons (Arrays, Hashes, Ranges).

Older Ruby had separate Fixnum and Bignum classes for small and large integers. They were merged into Integer in Ruby 2.4 and removed afterwards. Referring to Fixnum today raises uninitialized constant Fixnum (NameError). If a tutorial mentions them, it is outdated.

Everything is an object

Because values are objects, you can ask them questions. The most useful are class, is_a?, instance_of? and respond_to?.

Ruby Asking objects about themselves

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

is_a? is true for the object's class and its ancestors; instance_of? is true only for the exact class. respond_to? asks whether a method exists, regardless of class, and is the basis of duck typing (Duck Typing). The ancestors list shows the full inheritance chain: Integer, then Numeric, then the module Comparable, then Object, then Kernel (a module full of methods like puts), then BasicObject at the very top. Classes and modules are covered later in The Ruby Object Model.

Integer and Float

Ruby Integer versus Float

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Two things catch beginners. First, dividing two integers gives an integer (7 / 2 is 3); make at least one side a Float when you want a fraction. Second, 0.1 + 0.2 is 0.30000000000000004, not 0.3: that is how binary floating point works in every language. Round for display, or use Rational or BigDecimal for exact money-like values. Numbers goes into all of this.

Strings and symbols

Ruby String and Symbol side by side

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Use strings for text that comes from users or files, and symbols for fixed names such as option keys and statuses. Each symbol exists once, so comparing symbols is fast and they make good hash keys: { name: "Ada" } uses the symbol :name.

true, false and nil: truthiness

Conditions in Ruby (if, while, &&, !) need a value to decide on. Ruby's rule is the simplest of any mainstream language:

Only false and nil are falsy. Everything else is truthy.

Ruby What counts as true

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

0, the empty string, the empty array and even the string "false" are all truthy. If you come from JavaScript, Python or PHP, this is the big difference. To test emptiness, ask explicitly with empty?, zero? or nil?.

nil deserves attention. It is an object (the only instance of NilClass) with a few methods of its own, and it is what you get when something has no value: a missing hash key, an unassigned instance variable, the result of puts, a method that ends without a value.

Ruby nil is an object

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Because nil converts to an empty string, array and zero, it often slips through quietly until you call a method it does not have:

Ruby The classic nil error (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The output is main.rb:2:in '<main>': undefined method '+' for nil (NoMethodError). Whenever you see "for nil", something upstream returned nil and you did not expect it. Fix the cause (why is total nil?) rather than adding .to_i everywhere. The tools for dealing with nil on purpose are in Ternary, Safe Navigation and Short-Circuit.

Converting between types

Ruby never converts types behind your back for +. You decide, using explicit conversion methods: to_s, to_i, to_f, to_sym, to_a, to_r.

Ruby Conversions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The short forms (to_i, to_f) are forgiving: bad input quietly becomes 0, which can hide mistakes. The capitalized Kernel methods Integer() and Float() are strict and raise an exception if the text is not a valid number. Use the strict ones for user input.

Ruby Strict conversion rejects bad input (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

You get main.rb:1:in 'Kernel#Integer': invalid value for Integer(): "abc" (ArgumentError). The exception class is ArgumentError: the method received an argument of the right type with an unacceptable value. Ruby also refuses to guess when you mix types in arithmetic:

Ruby Mixing types in arithmetic (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The first line prints 555, because String#* repeats a string. The second fails with String can't be coerced into Integer (TypeError): Integer#+ tried to make the string into a number and gave up. Swap the order ("5" + 5) and the message becomes no implicit conversion of Integer into String. Either way the cure is to convert one side deliberately: 5 + "5".to_i or "5" + 5.to_s.

Comparing and testing types

You will often choose behavior from the type of a value. Prefer is_a? (or case/when, covered in case and when) over comparing class directly, because is_a? respects inheritance.

Ruby Choosing by type

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Notice when Integer: the case tests Integer === value, which is true when the value is an integer. Even so, Ruby code usually asks "can it do what I need?" (respond_to?) rather than "what class is it?". That habit is called duck typing, and it makes code reusable.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which of these values is falsy in Ruby?

    Only false and nil are falsy. 0, "" and [] are all truthy, unlike in JavaScript, Python or PHP.
  2. 2. What does 7 / 2 evaluate to?

    Dividing two Integers performs integer division and gives 3. Use 7.0 / 2 or 7.fdiv(2) for 3.5.
  3. 3. What is the difference between Integer("abc") and "abc".to_i?

    to_i is forgiving and returns 0 for text with no leading number. Integer() is strict and raises ArgumentError, which is what you want for validating input.
  4. 4. 5.instance_of?(Numeric) and 5.is_a?(Numeric) return what?

    5 is exactly an Integer, so instance_of?(Numeric) is false, but Integer inherits from Numeric, so is_a?(Numeric) is true.
  5. 5. What error does 5 + "5" raise?

    Ruby does not convert silently. The integer addition cannot coerce the string, so it raises TypeError.

Summary

  • Everything in Ruby is an object; ask it with class, is_a?, instance_of? and respond_to?.
  • The basic types are Integer (unlimited size), Float, String, Symbol, true, false and nil; Fixnum and Bignum no longer exist.
  • Only false and nil are falsy; 0, "" and [] are truthy.
  • Integer division truncates; floats are approximate (0.1 + 0.2).
  • to_i, to_f are forgiving; Integer() and Float() are strict and raise ArgumentError.
  • Mixing types in arithmetic raises TypeError; convert explicitly.
  • nil is an ordinary object, and "undefined method ... for nil" almost always means a value was missing earlier.

Next: Numbers