Skip character as arguments

I have already defined and working method, since

render_format(doc,host,table_info)

      

I called this method at some place where 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}")

      

It worked great.

Now I have to call this method like,

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 to 3), meaning it treats it all as one single argument. Why is this?

+3


source to share


1 answer


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

You can wrap each hash in your own curly braces to let Ruby know that they are in fact separate 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'} })



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

.

Alternatively, if you can change the implementation of the method in question, you can simply take one hash as an argument and separate the values ​​from the key inside the method.

+1


source







All Articles