On Tue, Apr 26, 2011 at 6:34 PM, Reginald Tan <redge.tan / gmail.com> wrote:
> Hi guys. I want my PStore to act more like a Hash. Basically I want to
> add "map" functionality to it. For a regular hash, you can do the
> following:
>
>
> h = {0 => "sword", 5 => "hammer", 3 => "arrow"}
> puts h.map{ |x| x[0]}.max  # gives the highest key which is 5
>
>
>
> I want pstore to be able to do same thing. I've included Enumerable but
> I do have to implement the each method which I dont know how to go
> about. Any suggestions? Thanks

It looks like, during a transaction, the content of a PStore is
represent by a Hash in the instance variable @table, so you if you
want the PStore to act like a Hash, something like this should work:

class PStore
  def each &blk
    in_transaction
    @table.each &blk
  end
end

(If you call this without a block, it looks like you get an enumerator
over the state of the store as of the transaction it was captured in,
which can be used outside of that transaction, and that could be
useful for some things.)

Obviously, this is exploiting details of the implementation rather
than the public interface, so it's at more risk of getting broken in a
new version of the library than would be an approach that relies only
on the public interface.

>
> class PStore
>  include Enumerable
>  def each &block
>
>  end
> end
>
> p = PStore.new("temp.store")
> p.transaction do
>  p[0] = "sword"
>  p[1] = "hammer"
>  p[2] = "arrow"
> end
>
> p.transaction do
>  puts p.map{|x| x[0]}.max # wont work yet
> end
>
> --
> Posted via http://www.ruby-forum.com/.
>
>