1. Equal?
We often need to compare two objects. Ruby provides a variety of methods for comparing objects. We can use equal? The method is used to compare whether two objects are the same. This method is used to compare whether two values point to the reference of the same object. For example:
A = "Ruby" # A String object. B = c = "Ruby" # Two string objects point to a reference. A. Equal? (B) # False: A and B are different objects. B. Equal? (C) # True: B and C point to the same reference.
This comparison method is to compare whether the IDs of two objects are the same. Obviously, A is an object, and B and C point to another object. Their object IDs are different:
A. object_id = B. object_id # is equivalent to a. Equal? (B)
2. = to compare whether objects are equal
His role and equal? The method is different. It compares whether the content of two objects is the same:
A = "Ruby" # define a String object
B = "Ruby" # Although the content of A is the same, they are different objects a. Equal? (B) # False: A and B point to different objects a = B # True: their content is the same
In addition to strings, arrays and dictionary classes also define the = Operator. If the number of elements in two arrays or dictionary objects is the same and each element is the same, the = returns true.
The numerics object performs a simple newest conversion during comparison, so the comparison results of fixnum Type 1 and float type 1.0 are equal.
Similarly, you can use it! = To determine whether two objects are unequal.
3. eql? Method
Ruby also provides eql? Method, it corresponds to equal? Is a more refined method.
4. Compare the three equal signs =
In general, this method is the same as =, but in some specific cases, = has a special meaning:
In range, = is used to determine whether the object on the right of the equal sign contains the range on the left of the equal sign;
The regular expression is used to determine whether a string matches the pattern,
Class Definition ===to determine whether an object is a class instance,
Symbol definition = to determine whether the symbol objects on both sides of the equal sign are the same.
(1 .. 10) ===5 # True: 5 belongs to range 1 .. 10
/\ D +/= "123" # True: string matching mode string = "S" # True: "S" is an instance of the string class: S = "S" # True