Ruby is a real object-oriented language, everything you manipulate is an object, and the results of the operations they return are also objects.
In Ruby, an instance is created by the constructor of a class. The standard constructor is new.
Song1 = Song.new ("Ruby Tuesday")
song2 = Song.new ("Enveloped in Python") # and so on
Although these instances are created by the same class, they each have unique characteristics.
First, they have a unique object identifier (simple understanding of the object ID).
Second, you can define the instance variables, and the values of the variables are unique within each instance.
These instance variables hold references to objects. For example, each song may have an instance variable that holds the title of the song.
Within a class, you can define an instance method. A method is a function block that can be invoked either inside or outside of a class, depending on the access constraints of the method.
An instance method can access an instance variable and get a reference to an object.
Method executes by sending a message to an object. The information contains the method name and the parameters required by the method.
When an object receives a message, it looks for the appropriate method in its own class. If found, call this method if it is not found ...
The business logic of these methods sounds more complicated, but it's natural to use them. Let's look at the invocation of some methods first.
"Gin Joint". Length-> 9
"Rick". Index ("C")-> 2
-1942.abs-> 1942 Sam.play
(song)-> "Duh dum, DA Dum de dum ... "
The difference between Ruby and most languages here deserves our attention. In Java, to get the absolute value of a number you need to call another method and pass the numbers in.
You might write this:
Number = Math.Abs (number)//Java code
In Ruby, a number is built with the ability to convert to absolute value. You just send the message abs to the number, it will automatically execute.
Number = Number.abs
When learning a new language, many people do not like to read the boring grammar, so let's go straight to the point.
Let's start with a simple Ruby program, and we'll write a method that returns a personal greeting. Then we call this method multiple times.
def say_goodnight (name) result
= "Good night," + Name return result End # time for
bed...
puts Say_goodnight ("Johnboy")
puts Say_goodnight ("Maryellen")