New Names For Old Things

Ruby uses special names for things that we already know. For instance, it uses the word Float to mean “decimals”. Here are more definitions:

  • Object: That’s just any piece of data. Like the number 3 or the string ‘hello’.
  • Class: Ruby separates everything into classes (or categories), such as integers, floats and strings.
  • Method: These are the things that you can do with an object. Think of it as the object’s “behaviour”. For example, you can add integers together, so + is an integer method. You can capitalize strings, so upcase is a string method.

You’ve already seen three classes for things that you already know (note that Ruby class names are capitalized):

Old name Ruby class
integer Integer
decimals Float
text String

You have also seen several methods:

Ruby class Some methods
Integer + – / * % **
Float + – / * % **
String capitalize, reverse, length, upcase

Classes vs. objects

Make sure you understand the difference between classes and objects. An object is a unit of data. A class is what kind of data it is.

For example, 3 and 5 are different numbers. They are not the same object. But they are both integers, so they belong to the same class. Here are more examples:

Object Class
2 Integer
-5 Integer
7.2 Float
3.14 Float
‘hello’ String
‘world’ String

Class#method notation

Remember, different classes have different methods. Here are some differences that you have already seen.

  • Division (/) doesn’t work the same with integers and floats.
  • Addition (+) doesn’t work the same with strings as it does with integers.
  • Strings have several methods that integers and floats don’t have (e.g., capitalize, length, and upcase).

For this reason, we will use the notation Class#method to state exactly which method we mean. For instance, I will say Integer#+ to differentiate it from Float#+ and String#+. I can also say that String#upcase exists, but Integer#upcase does not exist.

Converting between classes

Ruby has some methods for converting between classes:

Method Converts
From To
String#to_i String Integer
String#to_f String Float
Float#to_i Float Integer
Float#to_s Float String
Integer#to_f Integer Float
Integer#to_s Integer String

Examples:

shell> irb --simple-prompt
>> 34.to_s
=> "34"
>> "12".to_i
=> 12
>> "hello".to_i
=> 0
>> 27.2.to_i
=> 27
>> 3.to_f
=> 3.0

Exercises

Finding Accurate Averages A quick exercise to practice using floats.

 

Exercise Idea:
Add up the following numbers and find their average. Remember to use Floats in order to be as accurate as possible.
88
94
77
68
97

 
   

84.8

looks good to me :-)

same game
new numbers :-)

3
130
80
76
90

:-)