ruby Exercise Memo III (if, case, array, each by leap year)

Purpose

Let's actually write the code of ruby. This time is the third.

theme

Create the following method leap ?.

-** Function name : leap? - Input : year - Output **: true or false (true if year is a leap year)

(Issues in https://qiita.com/daddygongon/items/a550bde1ed6bff5217d8)

The code I wrote this time


def leap?(year)
  return  (year%400 == 0) ? true :
	    (year%100 == 0) ? false :
	      (year%4 == 0) ? true : false
end

[2004, 1999, 1900, 2000].each do |year|
  p year
  p leap?(year)
end

Commentary

Actually, I wrote the code with TDD in mind, but I will omit the work procedure. (I created it according to the procedure in the link above, so if you are interested, you can go there)

Explanation of code itself from here.

-** Contents of leap? ** Written with a ternary operator. Same as the code below.

```ruby
return case
   when year % 400 ==0 ; true
   when year % 100 ==0 ; false
   when year % 4 ==0   ; true
   else                ; false
   end
```

-** Contents of main loop ** [1900,2004,1999].each do |year| - endIs loop. Each element of the array [1900,2004,1999] is extracted in order. The extracted element is in year.

Reference material

Chart type ruby-III (if, case, Array.each by leap year)


Recommended Posts

ruby Exercise Memo III (if, case, array, each by leap year)
Ruby if, case
[Ruby] Leap year judgment program
Leap year judgment with Ruby
ruby exercise memo I (puts)
ruby exercise memo VI (hello class)