Shoud be easy - using hash key as a variable

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?

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
[email protected]

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs