equal?, eql?, ===, and ==의 차이

조회수 1877회

equal?, eql?, ===, and ==의 차이에 대해 알아보고 있습니다.

지금까지 알아낸건

  • ==는 default로 equal?메소드를 호출하고, 두 피연산자가 정확히 같은 객체일 경우 true를 return
  • ===는 default로 ==로 호출하니까 이것도 equal?을 호출해서 두 피연산자가 같은 객체인 경우 true를 return

eql?이 default로 뭘 하는건지는 아직 못알아냈고 이것도 그냥 뒤적거리면서 본거라 확신할 수는 없어요..

루비는 같음을 비교하는 방법이 많아서 뭐가 뭔지 헷갈립니다 ㅜ

1 답변

  • 좋아요

    0

    싫어요
    채택 취소하기

    정말로 정확하게 알고 싶으시다면 ruby-doc.org의 Object documentation를 보셔야 합니다.


    == — 일반적으로 쓰는 "equality"

    Equality — At the Object level, == returns true only if obj and other are the same object. Typically, this method is overridden in descendant classes to provide class-specific meaning.

    객체 관점에서, ==는 두 객체가 같을 때 true를 return합니다. 보통 이 메소드는 자식 클래스에서 override가 가능해, 클래스마다 다르게 구현되어 있습니다.

    === — case equality

    Case Equality – For class Object, effectively the same as calling #==, but typically overridden by descendants to provide meaningful semantics in case statements.

    #==와 유사합니다. 보통은 case문에서 쓰기위해 override합니다.

    case some_object
    when /a regex/
      # The regex matches
    when 2..4
      # some_object is in the range 2..4
    when lambda {|x| some_crazy_custom_predicate }
      # the lambda returned true
    end
    

    eql? — 해시 equality

    The eql? method returns true if obj and other refer to the same hash key. This is used by Hash to test members for equality. For objects of class Object, eql? is synonymous with ==. Subclasses normally continue this tradition by aliasing eql? to their overridden == method, but there are exceptions. Numeric types, for example, perform type conversion across ==, but not across eql?

    두 객체가 서로 같은 해시키를 가질 때 true를 return합니다. class 객체간에 eql?==와 같습니다. 수와 관련된 클래스를 제외한 Subclass에서도 이 성질은 유지됩니다.

    #수에서는 ==와 eql?은 다름
    1 == 1.0     #=> true
    1.eql? 1.0   #=> false
    

    equal? — identity 비교

    Unlike ==, the equal? method should never be overridden by subclasses as it is used to determine object identity (that is, a.equal?(b) if and only if a is the same object as b):

    ==랑은 달리, equal? 메소드는 subclass가 override할 수 없습니다. 이는 equal?이 객체의 identity를 비교하기 때문입니다.

    irb(main):027:0> m = "a"
    => "a"
    irb(main):028:0> n = "a"
    => "a"
    irb(main):029:0> m.equal?(n) #같은 값이지만 false
    => false
    irb(main):030:0> 
    irb(main):031:0* n = m #이제 m과 n이 같은 객체
    => "a"
    irb(main):032:0> m.equal?(n)
    => true
    irb(main):033:0> 
    

답변을 하려면 로그인이 필요합니다.

프로그래머스 커뮤니티는 개발자들을 위한 Q&A 서비스입니다. 로그인해야 답변을 작성하실 수 있습니다.

(ಠ_ಠ)
(ಠ‿ಠ)