[RUBY] 7th class: if, else

Reference site

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

if-else statement

Conditional branching used in various languages ​​as well as Ruby Basically with Python

if expression[then] 
formula...
[elsif expression[then]
formula... ]
...
[else
formula... ]
end

Works with or without movements in []

Just note that else if is written as elsif

Writing example:

if a=20
 b true
elsif c=30
 b true
else
 b false
end

Theme: Is it a leap year?

A program that displays whether the number entered is a leap year

・ Years that are divisible by 4 are leap years ・ However, a year divisible by 100 is not a leap year ・ In addition, a year divisible by 400 is a leap year.

First of all, whether it is divisible by 4

[2004, 1999].each do |year|
  p year
  if year % 4 == 0
    p true #True if divisible by 4(leap year)
  else
    p false #False if not divisible by 4(Not a leap year)
  end
end

The first line puts 2004 and 1999 in each year

Next, put in the process of whether it is divisible by 100

[1900, 2004, 1999].each do |year|
  p year
  if year % 100 == 0
    p false #False if divisible by 100
    next
  end
  if year % 4 == 0
    p true
  else
    p false
  end
end

When next is executed, the process after next is not executed and it shifts to the next iteration. It is a little different from break which interrupts the iteration itself.

Finally, put in the process of whether it is divisible by 400

def leap?(year)
  if year % 400 == 0
    p true #True if divisible by 400
  elsif year % 100 == 0
    p false
  elsif year % 4 == 0
    p true
  else
    p false
  end
end
[2000, 1900, 2004, 1999].each do |year|
  p year
  leap?(year)
end

By the way, I implemented it as a function leap?

EX

If you write neatly using case instead of if, it will be like this

def leap?(year)
  case
  when year % 400 ==0 ; p true
  when year % 100 ==0 ; p false
  when year % 4 ==0 ;   p true
  else ;                p false
  end
end

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

note

It is difficult to think about conditional branching in advance and implement it, but may it be better to implement it step by step?


Recommended Posts

7th class: if, else
11th class: Class
if else practice
9th class: assert_equal
10th class: Recursion
8th class: rake
5th class: Output
11th :: ruby_VI (hello class)
6th class: Variables, method
5th
6th
6th
It's not "else if" but "else" and "if"
9th
7th
[Ruby] If and else problems-with operators-
11th
9th
7th
11th
10th
10th
Special Lecture on Multi-Scale Simulation: 11th (class)