[Ruby] How to use is_a? Differences from kind_of? and instance_of ?. How to check the type and return a boolean value.

A method that checks the element type and returns true if it matches the specified type, false if it is different,

About the difference between is_a?, kind_of?, Instance_of?.

table of contents

  1. Usage and examples
  2. Main type types
  3. is_a? and kind_of? are the same
  4. Difference between is_a? and instance_of?
  5. What is a superclass?
  6. Notes on using is_a?

## Usage and examples Both methods are used in the same way.

· Receiver method (type)

Returns true if the receiver matches the type specified in the argument, false otherwise.

Example (is_a?)


arr = [1, 2, 3]

arr.is_a?(Array)
=> true

arr.is_a?(String)
=> false

Example (kind_of?)


arr = [1, 2, 3]

arr.kind_of?(Array)
=> true

arr.kind_of?(String)
=> false

Example (instance_of?)


arr = [1, 2, 3]

arr.instance_of?(Array)
=> true

arr.instance_of?(String)
=> false

### ▼ Actual use A method of branching processing for each variable type with an if statement can be considered.

Illustration


def _article_items
    if article_items.is_a?(Hash)
      [
        article_items.fetch('default') 
      ]
    elsif article_items.is_a?(Array)
      article_items
    else
      []
    end
  end

## Main type
Element example Type (class)
"string" String
100 Integer
1.23 Floot
[1, 2, 3] Array
1..3 Range
{:a=>1, :b=>2, :c=>3} Hash
class Class
module Module

## `is_a?` and `kind_of?` are the same The process is the same because `kind_of?` is an alias for `is_a?`. It is more common to use `is_a?`, Which has a small number of characters.
## Difference between `is_a?` and `instance_of?` There is a clear difference between `is_a?` and `instance_of?`.

-Instance_of?: Evaluate only the receiver ・ Is_a?: Superclass type is also evaluated

A superclass is the parent class of the current element's class. is_a? returns true even if the argument contains a superclass type.

An example is as follows. (Details of superclass will be described later)

python


arr = [1, 2, 3]

arr.is_a?(Object)
=> true

arr.instance_of?(Object)
=> false

When Object, which is a superclass of Array, is used as an argument, is_a? is true and instance_of? is false.


## What is a superclass?

Each element has a class, and the parent class of that class is the superclass.

For example

--Integer 1 class (type) is Integer. --The Integer superclass is Numeric, which represents all numbers. --Numeric's superclass is an Object that represents all the data. --The Object superclass is a BasicObject that has only basic functions such as identification and method specification. This is the highest class.

Hierarchical structure of classes


BasicObject
↓
Object
↓
String, Numeric, Module, Class,,,
            ↓
     Integer, Floot

(Reference) The superclass of the top class BasicObject is nil.

python


BasicObject.superclass
=> nil

** ▼ Relationship between elements and superclass **
element Type (class) Super class Super class super class
"string" String Object Basic Object
100 Integer Numeric Object
1.23 Floot Numeric Object
[1, 2, 3] Array Object Basic Object
1..3 Range Object Basic Object
{:a=>1, :b=>2, :c=>3} Hash Object Basic Object
class Class Object Basic Object
module Module Object Basic Object
nil NilClass Object Basic Object

## Precautions when using `is_a?` The basic operation is the same for both `is_a?` And `instance_of?`. Therefore, `is_a?`, Which has a small number of characters, is easy to use.

** ▼ Caution 1 **

Note that it will be true even if you specify a superclass as an argument, so if you specify an Object or Basic Object that corresponds to all the data, true will be returned.

python


obj = {:a=>1, :b=>2, :c=>3}
obj.is_a?(BasicObject)
=> true

100.is_a?(BasicObject)
=> true

"String".is_a?(BasicObject)
=> true

** ▼ Note 2 ** It specifies the class (type) of the superclass, and is false when the class name is specified.

python


class Aaa
end

##Class inheritance
class Bbb < Aaa
end

##Superclass class name is false
Bbb.is_a?(Aaa)
=> false

##If you specify the type, true is returned
Bbb.is_a?(Class)
=> true

Recommended Posts

[Ruby] How to use is_a? Differences from kind_of? and instance_of ?. How to check the type and return a boolean value.
How to return a value from Model to Controller using the [Swift5] protocol
How to use Ruby return
[ruby] How to assign a value to a hash by referring to the value and key of another hash
[Ruby] How to get the value by specifying the key. Differences between hashes, symbols and fetch
[Swift5] How to communicate from ViewController to Model and pass a value
[Java] How to convert from String to Path type and get the path
[Rails] How to create a table, add a column, and change the column type
[Ruby] How to convert from lowercase to uppercase and from uppercase to lowercase
[Ruby] Learn how to use odd? Even? And count the even and odd numbers in the array!
[Ruby] How to use gsub method and sub method
How to convert a value of a different type and assign it to another variable
[Ruby basics] How to use the slice method
[Ruby] How to use the map method. How to process the value of an object and get it by hash or symbol.
Pass arguments to the method and receive the result of the operation as a return value
[Ruby] How to get the tens place and the ones place
[Ruby] How to extract a specific value from an array under multiple conditions [select / each]
I want to return a type different from the input element with Java8 StreamAPI reduce ()
How to write a migration from Rails datetime type to date type
How to create a form to select a date from the calendar
How to create a placeholder part to use in the IN clause
[Java] How to convert a character string from String type to byte type
How to retrieve the hash value in an array in Ruby
[Ruby] How to retrieve the contents of a double hash
How to check the extension and size of uploaded files
9 Corresponds to the return value
Ruby: How to use cookies
How to pick up the input value by asynchronous communication and output the desired data from the server
How to run a Kotlin Coroutine sample from the command line
[Convenient to remember !!!] How to convert from LocalDate type to character string and from character string to LocalDate type
How to get and add data from Firebase Firestore in Ruby
The operator that was born to be born, instanceof (Java) ~ How to use the instanceof operator ~
How to check for the contents of a java fixed-length string
Method to describe by dividing into multiple methods How to pass arguments How to use return value Method overload Pass by value and pass by reference
How to operate IGV using socket communication, and the story of making a Ruby Gem using that method
How to download and run a Jar package directly from the Maven repository with just the command line
How to use the link_to method
How to use StringBurrer and Arrays.toString.
How to use the include? method
How to use EventBus3 and ThreadMode
[Ruby] Difference between is_a? And instance_of?
How to use the wrapper class
How to use Ruby on Rails
How to use equality and equality (how to use equals)
[Ruby] How to use any? Method
How to use Ruby inject method
How to use Java enum type
Declare a method that has a Java return value with the return value data type
How to check before sending a message to the server with Spring Integration
How to run a GIF file from the Linux command line (Ubuntu)
[Ruby] I want to extract only the value of the hash and only the key
How to get the setting value (property value) from the database in Spring Framework
How to change the value of a variable at a breakpoint in intelliJ
Android development, how to check null in the value of JSON object
How to create your own annotation in Java and get the value
[Ruby] I want to make an array from a character string with the split method. And vice versa.
[Note] [Beginner] How to write when changing the value of an array element in a Ruby iterative statement