메서드 선언 호출 방법

 

def sqrt(a)
  x = a*a
  return x
end

def add1(a,b)
  return a+b
end

def add2(a,b=10)
  return a+b
end

def showName1()
  puts "showName1"
end

def showName2
  puts "showName2"
end

puts sqrt(3)
puts add1(3,5)
puts add2(5)
puts add2(5,3)
showName1
showName2()

블럭인수, 가변길이 인수 전달

def meta(&b)
  b.call()
end

def metb(a, *b)
  print a, "\t", b
end

meta{print "블럭인수"}
metb(2, 3)
metb(3,5,6,3,5,3,65,3)

변수 스코프

num = 1

def showNums()
  num = 10
  puts num
end

showNums()
puts num

$gnum = 10

def showNums2()
  gnum = 10
  print gnum, "  ", $gnum, "\n"
end

showNums2()

alias showNums3 showNums2
showNums3()

alias $gnum2 $gnum
puts $gnum2

 

루비Ruby 반복문Loop statement

for문

for i in 1..10
  for j in 1..i
    print "*"
  end
  puts ""
end

a = [1,2,3,4,5]

for i in a
  print i,"  ", a[i], "\n"
end

until문

num = 100
until num < 10 do
  num-=1
  puts num
end

while문

num = 1
while num < 10 do
  num+=1
  puts num
end

next, redo, break, retry

for i in 1..100
  if i % 2 == 0 then
    print i
    next
  end
  if i > 80 then
    break
  end
end

for i in 1..100
  if i % 2 == 0 then
    print i
    i=101
    redo
  end
end

for i in 1..100
  if i % 10 == 0 then
    print i
    retry
  end
end

루비Ruby 제어문control statement

if elsif else 구문
조건이 맞을 경우 실행
elif나 else if 가 아니고 어설프게 elsif이다

score = 10
if score > 100 then
  print "점수는 빵점에서 100점까지입니"
elsif score > 90 then
  print score, "점 수 합격입니다"
elsif score > 60 then
  print score, "점, 겨우 합격입니다"
else
  print "불합격"
end

unless
조건이 틀릴 경우 실행

score = 10
unless score > 60 then
  print "불합격"
else
  print "합격"
end

case
케이스에 맞는 경우 실행
숫자범위와 무자열비교 모두 가능

score = 10
case score
when 0...60 then
  print "불합격"
when 60...90 then
  print "그냥 합격"
when 90..100 then
  print "우수 합격"
else
  print "0부터 100까지의 숫자를 입력하세요"
end
dep = "회계부"
case dep
when "경리부" then
  print "불합격"
when "기획부" then
  print "그냥 합격"
when "사업부" then
  print "우수 합격"
else
  print "이 부서는 안됩니"
end

ㅇㅇ