Code Walkthrough for a Ruby on Rails Newbie
I am trying to understand how to use a ruby on rails libra开发者_Python百科ry. I am new and can't even understand the most basic example. The library I am trying to use is called statsample. Can someone help walk me through what is going in this code snippet:
$:.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
There's a lot going on here, isn't there?
# 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
Generally you have to dig down into the implementation to see how those blocks are used. There are two basic formats for defining a block in Ruby:
some_method do
...
end
some_method { ... }
These two are equivalent but the curly-brace version is often used for the sake of brevity, as it easily collapses into a single line.
Blocks can be a bit confusing because they are simply bits of code that are executed at the will of the method they are passed to. They may never be actually executed, or might be executed once, or many times. The block can also be executed in different contexts. You need to pay careful attention to what the method is asking for in a block either by reading the documentation, or analysis of the implementation or other examples.
Generally something called Statsample::Vector
is defined in lib/statsample/vector.rb
according to what you've posted here, but it could also be defined in lib/statsample.rb
depending on the author's organizational strategy. The correlation between class or module name and filename is only driven by convention, not any particular technical requirement.
精彩评论