Easy way to determine leap year in ruby?

2019-03-23 08:34发布

Is there an easy way to determine if a year is a leap year?

9条回答
2楼-- · 2019-03-23 09:00
def leap_year?(num)
 if num%4 == 0 && num%100 != 0  
    true
 elsif num%400 == 0 
    true
 elsif num%4 == 0 && num%100 == 0 && num%400 != 0 
    false
  elsif num%4 != 0 
    false
  end
end 
puts leap_year?(2000)
查看更多
虎瘦雄心在
3楼-- · 2019-03-23 09:00

The variable n takes year to test and prints true if it's a leap year and false if it's not.

n=gets.to_i 
n%4==0 ? n%100==0 ? n%400 ?(puts true):(puts false) :(puts true) :(puts false)
查看更多
Emotional °昔
4楼-- · 2019-03-23 09:02

This one takes a range:

(starting..ending).each do |year|
  next if year % 4   != 0
  next if year % 100 == 0 && year % 400 != 0
  puts year
end

Source: Learn to Program by Chris Pine

查看更多
来,给爷笑一个
5楼-- · 2019-03-23 09:02

Using the least amount possible of comparisons, you could do this:

  • First/Longer version
def leap_year?(year)
  # check first if year is divisible by 400
  return true if year % 400 == 0
  year % 4 == 0 && year % 100 != 0
end
  • Shorter version

We can do the same check using short circuit OR (||):

def leap_year?(year)
  year % 400 == 0 || (year % 4 == 0 && year % 100 != 0)
end
查看更多
smile是对你的礼貌
6楼-- · 2019-03-23 09:06

Try this:

is_leap_year = year % 4 == 0 && year % 100 != 0 || year % 400 == 0
查看更多
姐就是有狂的资本
7楼-- · 2019-03-23 09:12

Use Date#leap?.

now = DateTime.now 
flag = Date.leap?( now.year ) 

e.g.

Date.leap?( 2018 ) # => false

Date.leap?( 2016 ) # => true
查看更多
登录 后发表回答