Thuta Learning
Ruby
BasicProgrammingBeginner

Data Types

RubyLesson 630 min

What you'll walk away with

  • Ask a value for its type with .class and tell Integer, Float, String, Symbol, TrueClass and NilClass apart
  • Explain integer division (7 / 2 is 3) and how Float and Rational differ from Integer
  • Explain that only nil and false are falsy, while 0 and "" are truthy
  • Show the difference between a string's length and bytesize with Myanmar text, and choose between to_i and Integer()

Explain it simply

Data types in plain words

A data type tells Ruby what kind of thing a value is and therefore what you can do with it. You can add numbers, shout a string with upcase and ask whether something is nil, but you cannot upcase a number. Ruby's everyday types are Integer for whole numbers, Float for decimals, String for text, Symbol for names, true and false for yes and no, and nil for no value. You rarely declare them: Ruby works the type out from how you write the value, and you can always ask with .class.

Problem → Why → Solution

The problem: the type you assumed is not the type you have

A teacher writes a script to average two scores: (7 + 8) / 2 prints 7 instead of 7.5, and the check 0.1 + 0.2 == 0.3 fails. Another script treats an empty form field "" as missing, but "".nil? is false and if name is true for an empty string. None of this is a Ruby bug: the value being handled has a different type from the one its author had in mind.

These mistakes show up in the worst form: not a crash but a slightly wrong answer. Learning to ask what type a value has is therefore one of the best early habits.

average_bug.rb
total_score = 7 + 8
average = total_score / 2     # expected 7.5
puts average                  # prints 7
puts 0.1 + 0.2 == 0.3         # false
puts "".nil?                  # false: "" is a String, not nil

The type decides the behaviour

Operators and methods take their behaviour from the class of the values they work on: Integer / Integer drops the fraction, Float arithmetic is binary, a String is text and nil is a value of its own. If you know the type you know the behaviour, and .class tells you the type.

Core concept: every value has a class

Every Ruby value belongs to a class, and that class is its data type. You ask for it with .class. The everyday ones are Integer, Float, String, Symbol, true and false, and nil, and later lessons add the collections Array, Hash and Range. Ruby has no separate "primitive" types; all of them are objects.

TypeExampleRemember
Integer42, 1_000Any size; / drops the fraction
Float3.14A binary approximation: 0.1 + 0.2 is not exactly 0.3
Rational1/3rHolds exact fractions
String"ruby"UTF-8 text that can be changed in place
Symbol:rubyAn immutable name; every :ruby is the same object
true / falseTrueClass, FalseClassThere is no class called Boolean
nilNilClassThe value that means "no value"

Whole-number arithmetic stays whole. 7 / 2 is 3 because Integer division drops the fraction, and for negative numbers it rounds toward negative infinity, so -7 / 2 is -4 (C and Java would say -3). Make one operand a Float, or call fdiv, to get 3.5. Integers can be as large as memory allows, so 2**100 is exact, while Floats are binary approximations and 0.1 + 0.2 prints 0.30000000000000004. For money, use integer cents or Rational.

true, false and nil: only nil and false are falsy, and everything else is truthy, including 0, "" and [], which all count as true in a condition. There is no class called Boolean: true is a TrueClass and false is a FalseClass. nil means "no value" and belongs to NilClass; it is not the same as "", an empty String that is a real value, and not the same as 0.

Strings and symbols: a String is a changeable sequence of characters, UTF-8 by default, so Myanmar text works. length counts characters (code points) and bytesize counts bytes: "မြန်မာ" has a length of 6 and a bytesize of 18. A Symbol such as :active is an immutable name; every :active in a program is the same object, which makes comparison fast and suits hash keys, while "active" creates a fresh String every time you write it. Without the magic comment # frozen_string_literal: true at the top of a file, string literals can be changed; Ruby 4.0.9 allows that and warns only when you run with -W:deprecated.

Mental model: value, class, behaviour
  1. Every value is an object
  2. .class names its type
  3. The class decides what methods work
  4. Only nil and false are falsy

Check .class (or use p) before guessing why a method fails.

General pattern: asking and converting types

ruby
value.class              # which type is this?
value.is_a?(Integer)     # is it that type, or a subtype?
Integer("42")            # strict conversion, raises on bad input
"42".to_i                # lenient conversion, 0 for bad input
nil.nil?                 # true only for nil

.class returns the type, and is_a? answers true or false for whether a value matches a type. A capitalised conversion method such as Integer() raises an error on bad input, while a method such as to_i converts leniently and gives 0 when nothing fits. nil? is true only for nil itself.

Example: telling types apart with .class

This program asks six values for their class and also tests integer division and truthiness. Before running it, predict how 7 / 2 differs from 7.fdiv(2) and whether 0 is truthy or falsy.

datatypes.rb
name = "Ruby"         # String
age = 25              # Integer
price = 10.99         # Float
is_fun = true         # TrueClass
nothing = nil         # NilClass
status = :active      # Symbol

puts name.class
puts age.class
puts price.class
puts is_fun.class
puts nothing.class
puts status.class
puts nothing.nil?
puts 7 / 2
puts 7.fdiv(2)
zero = 0
puts zero ? "0 is truthy" : "0 is falsy"

Code breakdown

  1. Integer or Float?age = 25 # Integer

    A number without a decimal point is an Integer. With a decimal point, as in price = 10.99, it is a Float, so 10 and 10.0 are different types.

  2. true has a class toois_fun = true # TrueClass

    Asking true for its .class gives TrueClass, and false gives FalseClass. There is no Boolean class, so writing true.is_a?(Boolean) raises a NameError.

  3. nil means no valuenothing = nil # NilClass

    nil is an object of class NilClass. nothing.nil? returns true, the most common way to test for nil. Do not confuse it with the text "nil", which is a String.

  4. A Symbolstatus = :active # Symbol

    A name that starts with a colon, such as :active, is a Symbol. Unlike a String it cannot be changed and it is a single object across the program, which suits names such as statuses and hash keys.

  5. Integer divisionputs 7 / 2

    Dividing two Integers gives an Integer: 7 / 2 is 3. 7.fdiv(2) returns a Float, 3.5. When you want a fractional result, use fdiv or 7.0 / 2.

  6. 0 is truthyputs zero ? "0 is truthy" : "0 is falsy"

    The ? : ternary picks the first text when the condition is true. In Ruby 0 is truthy, so you get "0 is truthy", unlike JavaScript or C where 0 counts as false.

You should see
String
Integer
Float
TrueClass
NilClass
Symbol
true
3
3.5
0 is truthy

Numbers: Integer, Float and Rational

The code below shows the behaviour of numbers one line at a time. % is the remainder, ** is the power operator, underscores as in 1_000_000 only make the number easier to read, and an r suffix as in 3r creates a Rational.

numbers.rb
puts 7 / 2
puts(-7 / 2)
puts 7 % 3
puts 7.fdiv(2)
puts 2**100
puts 0.1 + 0.2
puts((0.1 + 0.2).round(2))
puts 1/3r + 1/6r
puts 1_000_000

This code prints 3, -4, 1, 3.5, 1267650600228229401496703205376, 0.30000000000000004, 0.3, 1/2 and 1000000, in that order. Compare how 1/3r + 1/6r gives exactly 1/2 with what a Float would give.

Strings, symbols and bytes

A Myanmar character takes three bytes in UTF-8, so "မြန်မာ", which has 6 code points, is 18 bytes long. Ruby's length counts code points, so it does not always match the number of letters a reader sees; grapheme_clusters reports 4 in Ruby 4.0.9, which is still not the 2 syllables a Myanmar reader would count. Decide what you are counting before you set a limit on text.

text_types.rb
s = "မြန်မာ"
puts s
puts s.length
puts s.bytesize
puts s.grapheme_clusters.length
puts "héllo".length, "héllo".bytesize

word = "ruby"
word << "!"
puts word
puts word.frozen?
puts :ruby.equal?(:ruby)
puts "ruby".equal?("ruby")

The first four lines give the Myanmar text, 6, 18 and 4, and héllo gives 5 and 6. After that, ruby! shows the string was changed in place and false shows its literal is not frozen. The last two lines show that writing :ruby twice gives one object (true) while writing "ruby" twice gives two objects (false).

nil, truthiness and conversions

if and the ternary operator only ask whether a value is truthy or falsy; they do not ask whether it is true. To test for an empty string or a zero, use a precise method such as empty? or zero?. For conversions, methods such as to_i are lenient, while writing Integer("...") is strict.

truthiness.rb
zero = 0
empty = ""
nothing = nil
no = false
puts zero ? "truthy" : "falsy"
puts empty ? "truthy" : "falsy"
puts nothing ? "truthy" : "falsy"
puts no ? "truthy" : "falsy"
puts "".empty?
puts "".nil?
puts nothing.to_s.empty?
p nothing.to_a
conversions.rb
puts "42".to_i + 1
puts "3.7xyz".to_f
puts "abc".to_i
puts nil.to_i
puts "12abc".to_i
puts 42.to_s + "!"
puts Integer("42")
begin
  Integer("12abc")
rescue ArgumentError => e
  puts e.message
end

The first code prints truthy, truthy, falsy, falsy, true, false, true and []. The second prints 43, 3.7, 0, 0, 12, 42! and 42, and finally the message from Ruby 4.0.9: invalid value for Integer(): "12abc".

In real projects

Data types in real projects

Real programs spend much of their time moving data from one type to another. Text arrives from forms, files and the network as Strings, and code converts it. For example, a web form's age arrives as "30"; Integer("30") converts it strictly and raises on junk such as "3O", while "3O".to_i quietly returns 3. Careful code therefore uses strict conversion for user input and lenient conversion only where garbage is acceptable.

Money is the classic Float trap. Shops store prices as integer cents (1099) or as Rational and format them only for display, because a Float cannot represent 0.1 exactly. nil also deserves respect: a missing value from a database or a hash lookup is nil, and calling a String method on it raises NoMethodError. Ruby offers safe navigation (value&.upcase) and fallbacks (value || "default") for that, and both rely on nil being falsy while "" and 0 are not.

Common mistakes

Common beginner mistakes

1. Expecting 7 / 2 to be 3.5

Dividing two Integers drops the fraction, so an average shows 7 and no error appears. Write total.fdiv(count) or total / count.to_f. When either number is a Float, the result is a Float.

2. Treating 0 and "" as false

Coming from JavaScript, Python or C, people expect if count to be skipped for 0. In Ruby only nil and false are falsy, so if count runs for 0 as well. State your intent exactly: count.zero?, name.empty?, value.nil?.

3. Converting user input with to_i

"12abc".to_i returns 12 without complaint and "abc".to_i returns 0, so bad input slips through unnoticed. To check input strictly, use Integer("12abc"), which raises ArgumentError (invalid value for Integer(): "12abc").

Best practices

Best practices

  • Do not store money in a Float; use integer cents (for example 1099) or a Rational.
  • Use Symbols for hash keys and status values, and Strings only for text that is displayed.
  • When something behaves unexpectedly, type p value.class first; it instantly reveals a nil or a String that you took for an Integer.

Mini challenge

Mini challenge: a safe average

Write an average method that takes a total and a count and returns the Float average rounded to 2 decimals. When the count is zero it returns nil, and the caller can replace that nil with "no data".

  • average(total, count) divides Integers with fdiv and rounds to 2 decimals with round(2)
  • When count is zero it returns nil instead of dividing by zero
  • Use p to print average(7, 2), average(10, 3) and average(5, 0)
  • Store average(5, 0) || "no data" in label and print it with puts, and be able to explain why it works: nil is falsy
average.rb
# average.rb
def average(total, count)
  # TODO: return nil when count is zero
  # TODO: otherwise divide as Floats and round to 2 decimals
end

# TODO: use p to print three averages: (7, 2), (10, 3) and (5, 0)
# TODO: print "no data" when the average is missing (use ||)

Expected: The program prints these four lines: 3.5 3.33 nil no data

Show hint

return nil if count.zero? ends the method immediately when count is zero (the if is written as a modifier at the end of the line). For the rest use total.fdiv(count).round(2). p shows nil as nil, whereas puts nil prints an empty line, which is why p is the right choice here. x || "no data" gives "no data" only when x is nil.

Show solution
average.rb
def average(total, count)
  return nil if count.zero?
  total.fdiv(count).round(2)
end

p average(7, 2)
p average(10, 3)
p average(5, 0)
label = average(5, 0) || "no data"
puts label

Quick quiz 1 / 3

What does puts(-7 / 2) print?

Quick quiz 2 / 3

With s = "မြန်မာ", what do puts s.length and then puts s.bytesize print?

Quick quiz 3 / 3

How do Integer("12abc") and "12abc".to_i differ?

What to remember

  • Every value has a class, its data type, which you ask for with .class: Integer, Float, String, Symbol, TrueClass, NilClass; there is no class called Boolean
  • Integer / Integer drops the fraction (-7 / 2 is -4), so use fdiv or a Float operand, and remember that a Float cannot hold 0.1 + 0.2 exactly
  • Only nil and false are falsy, while 0, "" and [] are truthy, and nil is not the same as ""
  • A String's length counts code points and bytesize counts bytes, and to_i is lenient while Integer() is strict

Official Ruby Documentation — Ruby Documentation

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.

Data Types | Thuta Learning