On 8/14/05, Ara.T.Howard <Ara.T.Howard / noaa.gov> wrote:
> On Mon, 15 Aug 2005, Joe Van Dyk wrote:
> 
> > On 8/14/05, Ara.T.Howard <Ara.T.Howard / noaa.gov> wrote:
> >> On Sun, 14 Aug 2005, Joe Van Dyk wrote:
> >>
> >>>> On Sun, 14 Aug 2005, Joe Van Dyk wrote:
> >> <snip>
> >>> Thanks!  I shall study this code (there's a few new idioms that I
> >>> haven't used before) and report back early next week on the
> >>> performance improvements.
> >>
> >> try this one - it's another order of magnitude faster:
> >>
> >>
> >>      harp:~ > ruby a.rb
> >>      #<PlayerData:0xb75cc0b4 @to_s=nil, @data=[400, 1.0, 2.0, 3.0, 42], @to_bin=nil>
> >>      400
> >>      1.0
> >>      42
> >>      pid : 400, x_position : 1.0, y_position : 2.0, z_position : 3.0, foobar : 42
> >>      creations per second : 114797
> >>
> >>
> >>      harp:~ > cat a.rb
> >>      class PlayerData
> >>        class << self
> >>          def create(*a)
> >>            new(a.pack(FORMAT))
> >>          end
> >>        end
> >
> >
> > Why do you use 'class << self' here?
> 
> to define class methods.  in the context of a class think of it like
> 
>    class C
> 
>      class << self
> 
>        # now i'm in class def scope
> 
>      end
> 
>      # now i'm in instance def scope
> 
>    end
> 
> therefore you can
> 
>    class C
>      class << self
>        attr :foobar
>        alias barfoo foobar
>      end
>      attr :foobar
>      alias barfoo foobar
>    end
> 
> and then
> 
>    c = C::new
> 
>    p C::foobar
>    p C::barfoo
> 
>    p c.foobar
>    p c.barfoo
> 
> make sense?  the scoping makes things like 'attr' and 'alias' possible in the
> class scope.
> 
> so, for that method i'm defining a 'create' class method (instance factory)
> which is like 'new' but accepts normal arguments and packs them into a buffer.
> note that the new/initialize pair take a packed binary string as an argument -
> but that is terribly inconvenient for testing.  therefore i made the create
> method - i makes sense for it to be a class method (vs. a global method)
> because only the class knows the encoding of the string : encapsulation.

Isn't
def self.create(*a)
 ...

clearer than

class << self
  def create(*a)
 ... 

?  I mean, they both create a class method, right?