I’ve a method like:
def method (a=[],b=[])
...
end
I am calling this method with variables like this:
method(h[0].values_at("value"), h[1].values_at("value"))
where h[0] and h[1] are hashes. It works fine.
I dont know if h[1] is going to be there in the next run, so it’s giving me error if hash h[1] is not there.
How can I modify it so it makes the call dynamically depending on whether h[0], h[1] are there or not, and call the method with the correct number of parameters.
Hope I understood your problem right:
Your problem: if
h[1]does not exist,h[1].values_atwill raise an exception. So you have to test first, if the value is available. In the code snipllet above I used a ternary operator.An extended version would be:
With my solution you don’t need the default values in the method definition.
In your comment you extended your question.
With four parameters you could use it like this:
But I would recommend a more generic version:
And another – probably not so good – idea:
Extend nil (the result of
h[1]ifhhas not this element) to return[]for values_at: