# How can I access an attribute via a symbol?

**URL:** <https://www.ruby-forum.com/t/how-can-i-access-an-attribute-via-a-symbol/83808>\
**Category:** Rails\
**Created:** [March 19, 2006, 1:35am UTC](https://www.ruby-forum.com/t/how-can-i-access-an-attribute-via-a-symbol/83808 "2006-03-19T01:35:31Z")\
**Posts on this page:** 4\
**Page:** 1

<div class="post-metadata">

**Author:** ![pergesu](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/p/22d042/32.png) [@pergesu](https://www.ruby-forum.com/u/pergesu)\
**Post date:** [March 19, 2006, 1:35am UTC](https://www.ruby-forum.com/t/how-can-i-access-an-attribute-via-a-symbol/83808/1 "2006-03-19T01:35:31Z")

</div>

In my model I’d like to write a method that accesses the attributes by  
name. A very simple implementation would be

class MyModel \< ActiveRecord::Base  
def get\_value(attribute)  
return value\_of\_attribute  
end  
end

Then I can call it with m.get\_value(:name) to get the value of the  
name column in the db. I’m not sure what to put in for  
‘value\_of\_attribute’ though. How do I do that?

Pat

---

<div class="post-metadata">

**Author:** ![pergesu](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/p/22d042/32.png) [@pergesu](https://www.ruby-forum.com/u/pergesu)\
**Post date:** [March 19, 2006, 1:35am UTC](https://www.ruby-forum.com/t/how-can-i-access-an-attribute-via-a-symbol/83808/2 "2006-03-19T01:35:32Z")

</div>

Just use the [] accessor:

model = MyModel.find(1)  
value = model[:attribute\_name]

Cheers!

-DF

---

<div class="post-metadata">

**Author:** ![pergesu](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/p/22d042/32.png) [@pergesu](https://www.ruby-forum.com/u/pergesu)\
**Post date:** [March 19, 2006, 1:35am UTC](https://www.ruby-forum.com/t/how-can-i-access-an-attribute-via-a-symbol/83808/3 "2006-03-19T01:35:33Z")

</div>

What if I’m in the model?

I don’t want to just get the value of course…I want a method that  
will take the name of the attribute, process it a bit, and give the  
output.

Pat

---

<div class="post-metadata">

**Author:** ![pergesu](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/p/22d042/32.png) [@pergesu](https://www.ruby-forum.com/u/pergesu)\
**Post date:** [March 19, 2006, 2:14am UTC](https://www.ruby-forum.com/t/how-can-i-access-an-attribute-via-a-symbol/83808/4 "2006-03-19T02:14:56Z")

</div>

Hey Pat,

if you just want to get the value out of the AR attributes hash you  
use self[]

(in your model)

def upcase\_something(sym)  
self[sym].upcase  
end

## Regards, Trevor

Trevor S.  
[http://somethinglearned.com](http://somethinglearned.com)
