Ruby data type verification method

Asked 2 years ago, Updated 2 years ago, 26 views

Hi, how are you? I am a student who is learning Ruby these days.

I'd like to ask you how to check the data type in Ruby.

Python can be checked by type Ruby says the data type of the variable changes implicitly. Then is it impossible to check?

["John", "Eric", [Cleese", "Idle", "Michael", [Palin]] In this arrangement, When you say that you output each element with a for statement, you want to express the overlapping arrangement differently In Python, you could have added conditions for each element when the type was listed How do you do it in Ruby?

I ask for your answers...!!

ruby

2022-09-21 15:51

1 Answers

In ruby, you can print the type with .class and check if it is the same type with kind_of?.

The code below verifies that it is an array (kind_of?), or outputs its type (.class), and then outputs the value. If it is an array, write 'Array' and print the value.

arr= ['John', 'Eric', ['Cleese', 'Idle'], 'Michael', ['Palin']]

arr.each do |a|
   if a.kind_of?(Array)
       print("Arrange: #{a}"\n")
   else
       print("#{a.class}: #{a}\n")
   end
end


2022-09-21 15:51

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.