I am trying to understand how to use a ruby on rails library. 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?
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:
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::Vectoris defined inlib/statsample/vector.rbaccording to what you’ve posted here, but it could also be defined inlib/statsample.rbdepending 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.