Lesson Monday

So far, we've been creating objects using what's called literal notation. For example, to make an empty new String or Array, we type in the literal characters that are used to identify these classes:

> new_string = ""
> new_array = []

For example, creating a new String would be accomplished like this with literal notation:

> letters = "abc"

Using .new(), we could create the same string like this:

> letters = String.new()
> letters.concat("a")
> letters.concat("b")
> letters.concat("c")

Notice that the method .new() can be run on String. Even though it is a class, it is also an object. Remember...just about everything in Ruby is an object.

Here's another example. An Array using literal notation would look like this:

> numbers = [1, 2, 3]

And the same Array using .new would be created like this:

> numbers = Array.new()
> numbers.push(1)
> numbers.push(2)
> numbers.push(3)

Since the classes we have been working with like String and Array can be created with literal notation, it feels awkward to use the .new method with them. But not all classes have a literal notation option. To create objects from those classes, we will use the method .new().

Let's explore the class Time which does NOT have a literal notation option.

> now = Time.new()
=> 2014-10-13 15:36:04 -0700

When we create a new Time object using the .new() method without any arguments, the resulting value stores the year, month, day, hour, minute, second and offset from mean Greenwich time.

Note that a .new() method for any class will accept arguments for its properties. Time accepts arguments for each of the properties we saw in the default now values — year, month, day, etc. So, we can create new Time objects with arguments included like this:

> y2k = Time.new(2000)
=> 2000-01-01 00:00:00 -0800
> new_year = Time.new(2015, 1, 1)
=> 2015-01-01 00:00:00 -0800

Once defined, an object created with .new() can use methods from its class just as any object created with literal notation:

> now.hour()
=> 15
> now.min()
=> 36
> now.monday?()
=> false
> now.wednesday?()
=> true

Terminology


  • Literal notation: To create an object by typing in the literal characters that are used to identify these classes.

Example:

new_string = ""
new_array = []
  • .new(): A method that can be called on a type of object to create a new one.

Example:

numbers = Array.new()
letters = String.new()
now = Time.new()

Tips


Once defined, an object created with .new() can use methods from its class just as any object created with literal notation:

> now.hour()
=> 15
> now.min()
=> 36
> now.monday?()
=> false
> now.wednesday?()
=> true

Lesson 5 of 22
Last updated August 7, 2022