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

I have a Ruby method that looks for an array of hashes and returns a subset of this 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 only one action is returned, in which case I do not think that it returns an array with one element, but only the element itself. This becomes problematic later.

What is a good way to ensure that it returns an array of 1 element in this case?

Thank.

+3
source share
4 answers

selectalways returns an array (except that you are breakinside a block that you do not have). So, no matter what happens in your code, this is not the reason.

, @actions ( Enumerable), select , . , @actions . , , / @actions.

+2

, , :

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

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

[*b]
=> [4]
+14

, :

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

:

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

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

Array(b)
=> [4]
+1

Source: https://habr.com/ru/post/1737699/


All Articles