Open In App

Ruby | Date <=>() method

Last Updated : 09 Jan, 2020
Improve
Improve
Like Article
Like
Save
Share
Report

Date#<=> is a Date class method which compares two date objects.

Syntax: Date<=>b

Parameter: Date values

Return: 1 if a is greater than b
-1 if a is less than b
0 if a equals b

Example #1 :




# Ruby code for Date.<=>() method
  
# loading date
require 'date'
  
# declaring Date 
a = Date.new(2019, 1, 1)
  
# declaring Date
b = Date.jd(2452004)
  
# declaring Date
c = Date.ordinal(2019, 12)
  
# Date 
puts "Date a : #{a}\n\n"
puts "Date b : #{b}\n\n"
puts "Date c : #{c}\n\n\n\n"
  
  
# <=> form 
puts "Date a <=> form : #{a <=> c}\n\n"
puts "Date b <=> form : #{b <=> Rational(10, 2)}\n\n"
puts "Date c <=> form : #{c <=> Rational(10, 4)}\n\n"


Output :

Date a : 2019-01-01

Date b : 2001-04-04

Date c : 2019-01-12



Date a  form : -1

Date b  form : 1

Date c  form : 1

Example #2 :




# Ruby code for Date.<=>() method
  
# loading date
require 'date'
  
# declaring Date 
a = Date.parse('2019-01-01')
  
# declaring Date
b = Date.strptime('03-12-2019', '%d-%m-%Y')
  
# declaring Date
c = Date.commercial(2019, 5, 6)
  
  
# Date 
puts "Date a : #{a}\n\n"
puts "Date b : #{b}\n\n"
puts "Date c : #{c}\n\n\n\n"
  
  
# <=> form 
puts "Date a <=> form : #{a <=> c}\n\n"
puts "Date b <=> form : #{b <=> Rational(10, 2)}\n\n"
puts "Date c <=> form : #{c <=> Rational(10, 4)}\n\n"


Output :

Date a : 2019-01-01

Date b : 2019-12-03

Date c : 2019-02-02



Date a  form : -1

Date b  form : 1

Date c  form : 1



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads