How do I create an attribute accessor to do this

I want to be able to do this to merge a hash into attribute bas on
instance bar in class foo;

bar = Foo.new
bar.bas << { :this => "that" }

Is there any way to define the accessor in Foo to be able to do this?

Thanks,
James

J2M wrote:

I want to be able to do this to merge a hash into attribute bas on
instance bar in class foo;

bar = Foo.new
bar.bas << { :this => "that" }

Is there any way to define the accessor in Foo to be able to do this?

Thanks,
James

  class Hash
    alias :<<, :merge!
  end

  class Foo
    attr :bas
    def initialize
      @bas = {}
    end
  end

Is that what you had in mind?

T.

Hi --

I want to be able to do this to merge a hash into attribute bas on
instance bar in class foo;

bar = Foo.new
bar.bas << { :this => "that" }

Is there any way to define the accessor in Foo to be able to do this?

Here's one way. It involves assigning a hash to @bar, and adding the
<< behavior to that hash (using a module).

   require 'test/unit'

   class Foo

     attr_reader :bas

     module UpdateAppender
       def <<(other)
         update(other)
       end
     end

     def initialize
       @bas = {}.extend(UpdateAppender)
     end

   end

   class TestMerging < Test::Unit::TestCase
     def test_1
       f = Foo.new
       f.bas << { :this => "that" }
       assert_equal(f.bas.keys, [:this])
     end
   end

David

ยทยทยท

On Mon, 25 Sep 2006, J2M wrote:

--
                   David A. Black | dblack@wobblini.net
Author of "Ruby for Rails" [1] | Ruby/Rails training & consultancy [3]
DABlog (DAB's Weblog) [2] | Co-director, Ruby Central, Inc. [4]
[1] Ruby for Rails | [3] http://www.rubypowerandlight.com
[2] http://dablog.rubypal.com | [4] http://www.rubycentral.org

Thanks Trans, I will have a go tomorrow it is very late here in the UK
:slight_smile:

Thanks Trans, I will have a go tomorrow it is very late here in the UK
:slight_smile:

Thank you both for such quick responses. I will give this a go tomorrow
(v. late here in the UK).

David - thank you for all the time you take to help out us newbies, and
thank you for RailsConf Europe too - fan-tas-tic!