I have a Ruby method that searches an array of hashes and returns a subset of that array.
def last_actions(type = 'all')
actions = @actions
if type == 'run'
actions = actions.select {|a| a['type'] == "run" }
end
return actions
end
This works, except when there is only one action to return, in which case I don’t think it is returning an array with one element, but just the element itself.
This becomes problematic later.
What’s a good way to ensure it returns an array of 1 element in this case?
Thanks.
selectalways returns an array (except if youbreakinside the block, which you don’t). So whatever is going wrong in your code, this is not the reason.Of course if
@actionsdoes not contain an array (or another type of Enumerable), the call to select will cause an exception and the method will not return anything at all. The solution in that case would be to make sure that@actionsalways returns an array. How to do that depends on where/how you set@actions.