Check if 2 objects are equal

Hi
I havea a class with this structure. how do i check if 2 objects
instanialted from this class are equal. they could be separate
instantialtion but have exactly the same values?

class SymbolObject

def initialize(symb)
   puts symb
  @symbol=symb

@[email protected][email protected][email protected][email protected][email protected][email protected][email protected][email protected]=""
@markedBad=false
end
attr_accessor :symbol,:name ,:exchange, :news, :summary, :sector,
:industry,:category,:markedBad,:scanType,:otherInfo;
def to_s
return @symbol + @news + @exchange + @name
end

end

N Okia wrote:

Simple case, if both objects have same objectid, they are the same

 return @my_age <=> other.my_age

end
end

end

The simplest way to do this is:

def <=>(other)
return [@my_age, @my_first_name, @my_last_name] <=> [other.age,
other.my_first_name, other.my_last_name]
end

If you want to define equivalence for your classes, you really need to
do so yourself.

The easiest way is to make the class Comparable, and define your own
<=> operator. You can be as simple or as complex as you like:

class MyClass
include Comparable

attr_accessor :my_age, :my_first_name, :my_last_name

def initialize(age,first_name,last_name)
@my_age = age.to_i
@my_first_name = first_name
@my_last_name = last_name
end

def <=>(other)
# if the other class being compared is nil, we aren’t equivalent
return nil if other.nil?

# Simple case, if both objects have same objectid, they are the same
return 0 if object_id == other.object_id

# Define a heirarchy of tests for this class
if (@my_age == other.my_age)
  if (@my_first_name <=> other.my_first_name) == 0
    return @my_last_name <=> other.my_last_name
  else
    return @my_first_name <=> other.my_first_name
  end
else
  return @my_age <=> other.my_age
end

end

end

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs