독도 광고 모금 캠페인


'Dojo/Ruby'에 해당되는 글 3건

  1. 2008/04/27 피보나치
  2. 2008/04/27 소수구하기 (finding prime numbers)
  3. 2008/04/07 구구단
2008/04/27 16:57

피보나치

yield 활용

def fibonacci(max)
  n, m = 1,1
  while n<=max
    yield n
    n, m = m,n+m
  end

end

fibonacci(100) { |num| print num, " "}




Trackback 0 Comment 0
2008/04/27 15:53

소수구하기 (finding prime numbers)


첫 번째 버전
def getPrimeNumbers(maxValue)
  primes = Array.new
  primes.push(2)

  for x in 3..maxValue
    isPrime = true
    for prime in primes

      if Math.sqrt(x) < prime then
        next# continue
      end

      if x % prime == 0 then
        isPrime = false
        break
      end
    end

    if isPrime then
      primes.push(x)
    end
  end

  return primes

end




Trackback 0 Comment 0
2008/04/07 12:39

구구단


array의 each 메소드 이용

mul = (2...10).to_a
mul.each{|element| puts "2x"+element.to_s+"="+(2*element).to_s }


array의 each 메소드와 Proc 객체 활용

mul = (2...10).to_a
danproc = Proc.new{|element| mul.each{|m| puts element.to_s+"x"+m.to_s+"="+(element*m).to_s}}
danproc.call(2)


X.each do...end 활용

mul = (2...10).to_a
danproc = Proc.new{|element| mul.each{|m| puts element.to_s+"x"+m.to_s+"="+(element*m).to_s}}
(2...10).to_a.each do |danbase|
danproc.call(danbase)
end


또 다른 방법이 있으려나..?




Trackback 0 Comment 0