Hash as arguments of a method call

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!

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

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