[Ruby] What is an instance?

What is an instance?

Conclusion: A object (finished product) </ strong> made from a class (blueprint) </ strong>

Let's dig a little more concretely.

What is a class in the first place? ??

If you look up "class", it is often compared to "blueprint". If you chew a little more, it's like a box that stores the processing you want to do. In other words, if you store the process in a box called a class, you can easily call that process at any time.

The class can be defined as follows.

python


class Class name (first letter is uppercase)
end

And, in general, define a method called initialize in the class and initialize it.

python


def initialize()
Initialization process
end

Now, let's actually write the code. An example is given below. Let's create a class called User this time.

python


class User
  def initialize(name)
    @name = name
  end

  def introduction
    p "my name is#{@name}is."
  end
end

user1 = User.new("mataro") #Instantiate with new and argument ("mataro")give.
user2 = User.new("taro")  #Instantiate with new and argument ("taro")give.
user1.introduction #Output: "My name is mataro"
user2.introduction #Output result: "My name is taro"

By defining the process with class and instantiating it with new in this way, it becomes possible to create a finished product (instance) from the class.

Recommended Posts