# Attr\_writer and hash

**URL:** <https://www.ruby-forum.com/t/attr-writer-and-hash/109414>\
**Category:** Ruby\
**Created:** [July 14, 2007, 2:26pm UTC](https://www.ruby-forum.com/t/attr-writer-and-hash/109414 "2007-07-14T14:26:57Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![aidy](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/eada6e/32.png) [@aidy](https://www.ruby-forum.com/u/aidy)\
**Post date:** [July 14, 2007, 2:26pm UTC](https://www.ruby-forum.com/t/attr-writer-and-hash/109414/1 "2007-07-14T14:26:57Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![aidy](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/eada6e/32.png) [@aidy](https://www.ruby-forum.com/u/aidy)\
**Post date:** [July 14, 2007, 2:46pm UTC](https://www.ruby-forum.com/t/attr-writer-and-hash/109414/2 "2007-07-14T14:46:59Z")

</div>

On 7/14/07, aidy [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) 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

---

<div class="post-metadata">

**Author:** ![aidy](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/eada6e/32.png) [@aidy](https://www.ruby-forum.com/u/aidy)\
**Post date:** [July 14, 2007, 2:50pm UTC](https://www.ruby-forum.com/t/attr-writer-and-hash/109414/3 "2007-07-14T14:50:00Z")

</div>

> 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
