[RUBY] 7th

!Ubuntu-20.04.1!ruby-2.7.0p0

Conditional branch

These two are the ones I'm likely to use often

How to write an if statement

if conditional expression then
processing
elsif conditional expression then
processing
else
processing
end

It seems that then is not necessary. Neither else if, not elif, elsif.

How to write a case statement

case A
when 1 then  #When A is 1
processing
when 2 then  #When A is 2
processing
else         #When none of the above apply
processing
end

In this case as well, then may not be necessary.

Array

array = [] #Empty array
array = [1, 2, 3, 4, 5]

loop

Loops that I personally use often

How to write a for statement

Normal writing

for variable in object do
Process 1
Process 2
・
・
・
end

do does not have to be.

How to write to specify the range

for variable in 0..100 do
Process 1
Process 2
・
・
・
end

Repeat in the range of a to b in a..b. In this case, a is also included in b.

How to write a while statement

while conditional expression do
Process 1
Process 2
・
・
・
end

This also does not have to have do.

How to write each statement

object.each do |variable|
Process 1
Process 2
・
・
・
end

Iterate until there are no more elements in the object.

Try constellation judgment using if statement, array and for loop

Create a program that tells you the constellations when you give a birthday to the command line. Judgment is made by finding how many days have passed since the first day of Aries, 3/21.

days = [31,29,31,30,31,30,31,31,30,31,30,31]  #Number of days in a month
inter_star = [30,31,32,31,31,31,31,30,29,29,30,31]  #Days of each constellation(The beginning of Aries)
star_name = ["sheep", "Taurus", "Two", "Crab", "Lion", "Virgin", "Libra", "Scorpion", "Be", "goat", "Aquarius", "Uo" ]

birth_month = ARGV[0].to_i
birth_day = ARGV[1].to_i

sum = 0  #1/Variable to put the number of days from 1

for month in 0..(birth_month - 2)
  sum = sum + days[month]
end

sum = sum + birth_day

if sum < 81
  sum = sum + 366
end

sum = sum - 81  #First day of Aries 3/21 is 1/1 to 81 days

for month in 0..11
  sum = sum - inter_star[month]
  if sum < 0
    puts "#{ARGV[0]}Moon#{ARGV[1]}Born in Japan, you are "Aries"!"
    break
  end

  if sum < inter_star[month + 1]
    puts "#{ARGV[0]}Moon#{ARGV[1]}You born on the day#{star_name[month + 1]}It ’s a seat!"
    break
  end
end

At the command line

> ruby star.rb 7 24

If you enter

Born on July 24th, you are "Leo"!

The output was obtained.

Reference site

This article was created with reference to the following sites.

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


Recommended Posts