Skip to content

Instantly share code, notes, and snippets.

@Integralist
Created May 9, 2014 07:32
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Integralist/ac3eb133663d20a9fce1 to your computer and use it in GitHub Desktop.
Save Integralist/ac3eb133663d20a9fce1 to your computer and use it in GitHub Desktop.
Ruby Array Guarding

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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment