开发者

How to make sure a method returns an array, even when there is only one element in Ruby

开发者 https://www.devze.com 2022-12-23 17:51 出处:网络
I have a Ruby method that searches an array of hashes and returns a subset of that array. def last_actions(type = \'all\')

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.

W开发者_JAVA百科hat's a good way to ensure it returns an array of 1 element in this case?

Thanks.


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]


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.


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


You can also do it like this:

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

Array(a)
=> [1, 2, 3]

Array(b)
=> [4]
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号