views:

70

answers:

3

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.

+1  A: 

select always returns an array (except if you break inside the block, which you don't). So whatever is going wrong in your code, this is not the reason.

Of course if @actions does 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 @actions always returns an array. How to do that depends on where/how you set @actions.

sepp2k
You are quite right. I was later on handling the return value with .last, and that was the culprit. Thank you.
doctororange
+1  A: 

Your observation is more than strange, however you could try this:

def last_actions(type = 'all')
  actions = @actions.dup || []
  actions.delete_if {|a| a['type'] != "run" } if type == 'run'
  actions
end
hurikhan77
+4  A: 

Note that there is a nice clean ruby idiom to ensure single objects and arrays are treated as arrays:

a = [1,2,3]
b = 4

[*a]
=> [1, 2, 3]

[*b]
=> [4]
+1 for the coolness factor
hurikhan77