Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if variable is Date or Time or DateTime in Ruby?

Any easy way to check if a variable / object is of Date / Time / DateTime type? Without naming all the types

like image 322
Aurimas Avatar asked Jun 22 '16 19:06

Aurimas


People also ask

What does .first mean in Ruby?

The first() is an inbuilt method in Ruby returns an array of first X elements. If X is not mentioned, it returns the first element only. Syntax: range1.first(X) Parameters: The function accepts X which is the number of elements from the beginning. Return Value: It returns an array of first X elements.

What is time now in Ruby?

Ruby | Time now() function The now() is an inbuilt method in Ruby returns the current time.


2 Answers

Another option:

def is_datetime(d)
  d.methods.include? :strftime
end

Or alternatively:

if d.respond_to?(:strftime)
  # d is a Date or DateTime object
end 
like image 66
zeke Avatar answered Sep 21 '22 15:09

zeke


you can inspect the class of a object doing

object.class

It should return Date, String or whatever it is. You can also do the reverse and check if an object is an instance of a class:

object.instance_of?(class)

where class is the one you want to check (String, Date), returning true/false

like image 25
Ronan Lopes Avatar answered Sep 19 '22 15:09

Ronan Lopes