Ruby에 kind_of? / instance_of? / is_a? 의 차이점

조회수 3502회

kind_of? / instance_of? / is_a?가 어떻게 다른지, 언제 쓰는지 알고 싶습니다.

1 답변

  • 좋아요

    0

    싫어요
    채택 취소하기

    kind_of?is_a?는 같습니다.

    kind_of / is_a

    classobj의 클래스인 경우, 혹은 classobj의 superclass거나ㅓ obj에 포함되어 있는 모듈인 경우 true를 return합니다.

    instance_of?

    객체가 정확히 해당 클래스의 instance일때만 true를 return합니다. (상속에서도 false)

    예를들면

    puts 5.is_a? Integer #true
    puts 5.kind_of? Integer #true
    puts 5.instance_of? Integer #false
    

    출처 - ruby-doc :

    kind_of?

    • kind_of?(class) → true or false

    Returns true if class is the class of obj, or if class is one of the superclasses of obj or modules included in obj.

    is_a?

    • is_a?(class) → true or false

    Returns true if class is the class of obj, or if class is one of the superclasses of obj or modules included in obj.

    instance_of?

    • instance_of?(class) → true or false

    Returns true if obj is an instance of the given class. See also Object#kind_of?.

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

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

(ಠ_ಠ)
(ಠ‿ಠ)