2011-05-11 2 views
0

레일즈 라이브러리에서 루비를 사용하는 방법을 이해하려고합니다. 나는 새롭고 가장 기본적인 예를 이해할조차 수 없습니다. 내가 사용하려고하는 라이브러리를 statsample이라고합니다. 누군가이 코드 스 니펫의 내용을 통해 나를 안내 할 수 있습니까?Ruby on Rails를위한 코드 연습 Newbie

$:.unshift(File.dirname(__FILE__)+'/../lib/') 
require 'statsample' 

    Statsample::Analysis.store(Statsample::Dataset) do 
     samples=1000 
     a=Statsample::Vector.new_scale(samples) {r=rand(5); r==4 ? nil: r} 
     b=Statsample::Vector.new_scale(samples) {r=rand(5); r==4 ? nil: r} 

     ds={'a'=>a,'b'=>b}.to_dataset 
     summary(ds) 
    end 

    if __FILE__==$0 
     Statsample::Analysis.run_batch 
    end 

답변

3

여기에 많은 것이 있습니까?

# Add the lib/ directory to the require search path 
$:.unshift(File.dirname(__FILE__)+'/../lib/') 

# Load in the statsample file which presumably defines Statsample 
# This file may require others as necessary 
require 'statsample' 

# This makes a call to Statsample::Analysis.store with a block provided 
Statsample::Analysis.store(Statsample::Dataset) do 
    samples=1000 

    # This calls something to do with Statsample::Vector but the implementation 
    # would define exactly what's going on with that block. Not clear from here. 

    a = Statsample::Vector.new_scale(samples) {r=rand(5); r==4 ? nil: r} 
    b = Statsample::Vector.new_scale(samples) {r=rand(5); r==4 ? nil: r} 

    # Converts a simple hash with 'a' and 'b' keys to a dataset using some kind 
    # of Hash method that's been added by the statsample implementation. 
    ds = { 'a'=>a,'b'=>b }.to_dataset 

    # Calls a method that sets the summary to the hash 
    summary(ds) 
end 

# __FILE__ => Path to this source file 
# $0 => Name of script from command line 
# If the name of this file is the name of the command... 
if __FILE__==$0 
    # ..run batch. 
    Statsample::Analysis.run_batch 
end 

일반적으로 이러한 블록이 어떻게 사용되는지 보려면 구현을 조사해야합니다. 루비에서 블록을 정의하는 두 가지 기본 형식이 있습니다

some_method do 
    ... 
end 

some_method { ... } 

이 두 가지가 동일하지만 쉽게 하나의 라인으로 붕괴로 곱슬 중괄호 버전은 종종 간결하게하기 위해 사용된다.

블록은 전달되는 메서드의 의지에 따라 실행되는 코드 비트이기 때문에 약간 혼란 스러울 수 있습니다. 실행되지 않거나 한 번 또는 여러 번 실행될 수 있습니다. 블록은 다른 컨텍스트에서도 실행될 수 있습니다. 이 방법이 문서에서 읽거나 구현 또는 다른 예제를 분석하여 블록에서 요구하는 것에주의를 기울여야합니다.

일반적으로 여기에 게시 한 내용에 따라 이 lib/statsample/vector.rb에 정의되어 있지만 작성자의 조직 전략에 따라 lib/statsample.rb에 정의 할 수도 있습니다. 클래스 또는 모듈 이름과 파일 이름 간의 상관 관계는 특정 기술 요구 사항이 아닌 관례에 따라 결정됩니다.

+1

나를 두들겨라 - 나는 2/3에 불과했다. 좋은 설명이지만 – Kelly