« Back to Index

Ruby Array Guarding

View original Gist on GitHub

Ruby Array Guarding.md

Below is an example of trying to protect against a request for data failing to return the expected data structure (in this case an Array)…

expect_an_array_back = SomeClass.make_a_request_for_data

if expect_an_array_back.any?
  expect_an_array_back.each do |user|
    # ...
  end
end

Instead we should guard against failing in a cleaner way.

If the collection is empty then we can just loop over the Array without a guard, like so…

SomeClass.make_a_request_for_data.each do |user|
  # ...
end

Or in situations where we’re not sure if we’ll get an empty Array or nil then we can wrap the returned value in an Array and if it is nil then Array(expect_an_array_back) will be converted into an empty collection (which will be safe to enumerate), like so…

expect_an_array_back = SomeClass.make_a_request_for_data

Array(expect_an_array_back).each do |user|
  # ...
end