a = "hello" b = "hello" puts a == b puts a.equal?(b)
The == operator compares the content of the strings, so it returns true because both strings have the same characters.
The equal? method checks if both variables refer to the exact same object in memory. Since a and b are two different string objects with the same content, equal? returns false.
x = 1000 y = 1000 puts x == y puts x.equal?(y)
The == operator compares the values, so it returns true because both x and y are 1000.
The equal? method checks if both variables point to the same object. For integers larger than a certain range, Ruby creates separate objects, so equal? returns false.
sym1 = :ruby sym2 = :ruby puts sym1 == sym2 puts sym1.equal?(sym2)
Symbols with the same name are the same object in Ruby.
Therefore, both == and equal? return true.
arr1 = [1, 2, 3] arr2 = arr1.dup puts arr1 == arr2 puts arr1.equal?(arr2)
The == operator compares the content of the arrays, which are the same, so it returns true.
The equal? method checks if both variables point to the same object. Since dup creates a new object, equal? returns false.
str1 = "hello" str2 = str1 str2 << " world" puts str1 puts str2 puts str1.equal?(str2)
Both str1 and str2 point to the same string object.
Appending " world" to str2 modifies the object itself, so str1 also shows the change.
equal? returns true because both variables reference the same object.