# Shoud be easy - using hash key as a variable

**URL:** <https://www.ruby-forum.com/t/shoud-be-easy-using-hash-key-as-a-variable/172888>\
**Category:** Rails\
**Created:** [July 29, 2009, 1:43pm UTC](https://www.ruby-forum.com/t/shoud-be-easy-using-hash-key-as-a-variable/172888 "2009-07-29T13:43:43Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![convan23](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/8dc957/32.png) [@convan23](https://www.ruby-forum.com/u/convan23)\
**Post date:** [July 29, 2009, 1:43pm UTC](https://www.ruby-forum.com/t/shoud-be-easy-using-hash-key-as-a-variable/172888/1 "2009-07-29T13:43:43Z")

</div>

So I’ve taken a break from programming for a couple years and trying  
to get back into it, feeling quite like trying to ride a bike through  
the mud.

What I’m trying to do is use a variable as a hash key, like so:

def time\_advance(date,advance\_by,unit)  
return date.to\_time.advance({ advance\_by =\> unit.to\_i})  
end

function being called would look something like this - time\_advance  
(“Tue Aug 04 22:41:00 UTC 2009”,“weeks”,“3”), so the function being  
called would look like this if I hard-wrote it in:

“Tue Aug 04 22:41:00 UTC 2009”.to\_time.advance({ :weeks =\> “3”.to\_i })

How do I do?

---

<div class="post-metadata">

**Author:** ![convan23](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/8dc957/32.png) [@convan23](https://www.ruby-forum.com/u/convan23)\
**Post date:** [July 29, 2009, 4:31pm UTC](https://www.ruby-forum.com/t/shoud-be-easy-using-hash-key-as-a-variable/172888/2 "2009-07-29T16:31:26Z")

</div>

convan23 wrote:  
[…]

> What I’m trying to do is use a variable as a hash key, like so:
> 
> def time\_advance(date,advance\_by,unit)  
> return date.to\_time.advance({ advance\_by =\> unit.to\_i})  
> end

I think this should work, although you might want advance\_by.to\_sym to  
make sure that the key is a symbol. Also remember that you don’t need  
the curly braces around the hash if it’s the last (or only) argument.

## Best,

Marnen Laibow-Koser  
[http://www.marnen.org](http://www.marnen.org)  
removed\_email\_address@domain.invalid
