Forum: Ruby attr_writer and hash

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
F09f7d15d9fefc2cf68c4057694c8930?d=identicon&s=25 aidy (Guest)
on 2007-07-14 14:26
(Received via mailing list)
Hi,

class Test
 attr_writer :username, :password
  def initialize
    h = {:username => 'user', :password => 'pass'}
  end
end

t = Test.new
p t.h[username]


I am trying to access a hash key after instantiating the Test class,
but I am having a slight problem.

Could someone please direct me?

Thanks

Aidy
289cf19aa581c445915c072bf45c5e25?d=identicon&s=25 Todd Benson (Guest)
on 2007-07-14 14:46
(Received via mailing list)
On 7/14/07, aidy <aidy.rutter@gmail.com> wrote:
> p t.h[username]
>
>
> I am trying to access a hash key after instantiating the Test class,
> but I am having a slight problem.
>
> Could someone please direct me?
>
> Thanks
>
> Aidy

class Test
  attr_accessor :h
  def initialize
    @h = { :username => 'user', :password => 'pass }
  end
end

attr_accessor means you can read and write to the object.  The object
in this case is the hash, not the key or value.  Does that make sense?

hth,
Todd
D86ec78a7a258246684d15e09e51a170?d=identicon&s=25 Sharon Phillips (Guest)
on 2007-07-14 14:50
(Received via mailing list)
> p t.h[username]
>
>
> I am trying to access a hash key after instantiating the Test class,
> but I am having a slight problem.
>
> Could someone please direct me?
>
> Thanks
>
> Aidy

Hi Aidy,

It looks like you're mixing two different ways of getting at username
and password here.
Here are two separate approaches you could try

class Test
   attr_accessor :username, :password

   def initialize
     @username= 'user'
     @password= 'pass'
   end
end

t= Test.new
puts t.username
puts t.password

class Test2
   attr_accessor :details

   def initialize
     @details= {:username => 'user', :password => 'pass'}
   end
end

t= Test2.new
puts t.details[:username]
puts t.details[:password]


I think the problem with your code is a missing colon before
username. Should be p t.h[:username]

Cheers,
Dave
This topic is locked and can not be replied to.