Ruby Examples

This commit is contained in:
2026-01-15 14:01:21 +09:00
commit cf3d7d3296
76 changed files with 1191 additions and 0 deletions

17
level2/11.rb Executable file
View File

@@ -0,0 +1,17 @@
#!/usr/bin/ruby
# -*- coding: utf-8 -*-
=begin
두 수를 받아 더한 값을 반환하는 메서드 작성
=end
def add(a, b)
a + b
end
print "숫자 1: "
number1 = gets.chomp.to_i
print "숫자 2: "
number2 = gets.chomp.to_i
puts "#{number1} + #{number2} = #{add(number1, number2)}"

12
level2/12.rb Executable file
View File

@@ -0,0 +1,12 @@
#!/usr/bin/ruby
# -*- coding: utf-8 -*-
=begin
세 수 중 최댓값을 반환하는 메서드
=end
def max(a, b, c)
[a, b, c].max
end
puts "Max = #{max(5, 2, 9)}"

12
level2/13.rb Executable file
View File

@@ -0,0 +1,12 @@
#!/usr/bin/ruby
# -*- coding: utf-8 -*-
=begin
숫자를 받아 절댓값을 반환하는 메서드
=end
def abs(a)
a.abs
end
puts "Abs = #{abs(-7)}"

14
level2/14.rb Executable file
View File

@@ -0,0 +1,14 @@
#!/usr/bin/ruby
# -*- coding: utf-8 -*-
=begin
문자열을 받아 길이를 반환하는 메서드
=end
def len(s)
s.length
end
print "?"
s = gets.chomp
puts "#{s}의 길이는 #{len(s)}"

12
level2/15.rb Executable file
View File

@@ -0,0 +1,12 @@
#!/usr/bin/ruby
# -*- coding: utf-8 -*-
=begin
원의 반지름을 받아 넓이를 계산하는 메서드
=end
def area(r)
Math::PI * r ** 2
end
puts "Area = #{area(2)}"

12
level2/16.rb Executable file
View File

@@ -0,0 +1,12 @@
#!/usr/bin/ruby
# -*- coding: utf-8 -*-
=begin
나이를 받아 성인/미성년자 판별 메서드
=end
def adult?(age)
age >= 20
end
puts adult?(13) ? "성인입니다." : "미성년자입니다."

12
level2/17.rb Executable file
View File

@@ -0,0 +1,12 @@
#!/usr/bin/ruby
# -*- coding: utf-8 -*-
=begin
문자열과 반복 횟수를 받아 반복 출력하는 메서드
=end
def repeat(s, i)
s * i
end
puts repeat("도깨비", 6)

16
level2/18.rb Executable file
View File

@@ -0,0 +1,16 @@
#!/usr/bin/ruby
# -*- coding: utf-8 -*-
=begin
BMI 계산 메서드 작성
=end
def bmi(kg, cm)
weight = kg.to_f
height = cm.to_f / 100
weight / (height ** 2)
end
puts "BMI = #{bmi(70, 170)}" # 24.22
puts "BMI = #{bmi(75, 175)}" # 24.5

12
level2/19.rb Executable file
View File

@@ -0,0 +1,12 @@
#!/usr/bin/ruby
# -*- coding: utf-8 -*-
=begin
비밀번호 길이가 8자 이상인지 검사하는 메서드
=end
def password_valid?(pw)
pw.length >= 8
end
puts password_valid?("dfjirgaofmrioa") ? "OK" : "Nope"

19
level2/20.rb Executable file
View File

@@ -0,0 +1,19 @@
#!/usr/bin/ruby
# -*- coding: utf-8 -*-
=begin
윤년 여부를 판단하는 메서드
## 윤년의 조건
1. 서력 기원 연수가 004로 나누어 떨어지는 해는 윤년으로 한다.
2. 서력 기원 연수가 100으로 나누어 떨어지는 해는 평년으로 한다.
3. 서력 기원 연수가 400으로 나누어 떨어지는 해는 윤년으로 둔다.
=end
def leap_year?(year)
year %4 == 0 && (year %100 != 0 || year %400 == 0)
end
puts leap_year?(2000) ? "윤년" : "평년"
puts leap_year?(2020) ? "윤년" : "평년"
puts leap_year?(2025) ? "윤년" : "평년"