# Hash as arguments of a method call

**URL:** <https://www.ruby-forum.com/t/hash-as-arguments-of-a-method-call/122911>\
**Category:** Rails\
**Created:** [December 12, 2007, 9:01pm UTC](https://www.ruby-forum.com/t/hash-as-arguments-of-a-method-call/122911 "2007-12-12T21:01:52Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![casper\_the\_ghost](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/58956e/32.png) [@casper\_the\_ghost](https://www.ruby-forum.com/u/casper_the_ghost)\
**Post date:** [December 12, 2007, 9:01pm UTC](https://www.ruby-forum.com/t/hash-as-arguments-of-a-method-call/122911/1 "2007-12-12T21:01:52Z")

</div>

Hi all,

I’m writing a new class, and in the initialize I have:  
class Statement  
def initialize(\*args)  
@args = args[0]  
@args[:start\_at] = 30.days.ago if @args[:start\_at].nil?  
@args[:finish\_at] = Date.today if @args[:finish\_at].nil?  
@customer = Customer.find(@args[:customer\_id])  
end

(…)

end

This allows me, as you can see, to use @args[:customer\_id] for example  
to read arguments passed to the initialize. This is helpful in case I  
need to add some more arguments to my method without breaking existing  
calls.

This code is currently working (did not test it very long).

My question is: Why do I have to do the @args = args[0] thingy? I  
mean, I noticed that args was an Array instead of a hash, so thats why  
I did it. Is this correct? It doesnt look good…

Thanks!

---

<div class="post-metadata">

**Author:** ![casper\_the\_ghost](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/58956e/32.png) [@casper\_the\_ghost](https://www.ruby-forum.com/u/casper_the_ghost)\
**Post date:** [December 12, 2007, 9:27pm UTC](https://www.ruby-forum.com/t/hash-as-arguments-of-a-method-call/122911/2 "2007-12-12T21:27:35Z")

</div>

what you define here is a variable length argument list  
you get all argument passed as an array, not a hash

you could call it like:  
initialize({:a=\>1,:b=\>2},{:a=\>3,:b=\>4})  
and get an array with two hashes

to pass a single hash, you can use a simple parameter  
def initialize(args\_hash)  
call it with the hash  
initialize({:start\_at =\> 'whatever, :finish\_at =\> ‘now’})  
or  
initialize(:start\_at =\> 'whatever, :finish\_at =\> ‘now’)  
since you can omit the curly braces for the last or only  
hash argument
