Niyanta
Niyanta

Reputation: 473

Pass symbol as Arguments

I have an already defined and working method as,

render_format(doc,host,table_info)

I had this method called at some location wherein I passed the arguments as,

render_format("Daily Transactions in POS", {:doc => xml,:schema_name => "#{schema_name}",:store_code => "#{store_code}"}, :sales_log => "#{sales_log}")

This worked just fine.

Now I have to call this method as,

render_format(:doc => xml,:host => "bhindi.rw:3000",:table_info => {'hdr' => 'pos_invoices', 'line' => 'pos_invoice_lines', 'id' => 'pos_invoice_id', 'check_image_flag' => 'Y'})

But this gives ArgumentError, wrong number of Arguments(1 for 3) that is to say that it is treating the whole of that as one single argument. Why is that?

Upvotes: 3

Views: 1872

Answers (1)

p4sh4
p4sh4

Reputation: 3291

When you use a hash as the last (or only) method argument in the list Ruby allows you to omit the curly braces. In your first call, the arguments are of different types (strings and hashes), so Ruby understands that these are the several parameters. But in the second call, each of your parameters is a hash with only one key-value pair, but because of the optional outside curly braces Ruby interprets it as one hash, giving you the ArgumentError.

You can wrap each hash in its own curly braces letting Ruby know that they are in fact individual separate hashes:

render_format({ :doc => xml }, { :host => "bhindi.rw:3000" }, { :table_info => {'hdr' => 'pos_invoices', 'line' => 'pos_invoice_lines', 'id' => 'pos_invoice_id', 'check_image_flag' => 'Y'} })

You can actually see this in action in your first method call - the second argument hash is wrapped in its own curly braces, while the last one is not. If you omitted the outer curly braces on the second argument, Ruby would interpret the second and third arguments as one hash and give you an ArgumentError, wrong number of Arguments(2 for 3) error.

Alternatively, if you can change the implementation of the method in question, you can just accept one hash as an argument and separate the values by key inside the method.

Upvotes: 1

Related Questions