Previous posts arrays and arrays2

Based on a post by barkingiguana, some idiomatic ruby ways to handle arrays. Ruby tries to have a natural language style, preferring to be more expressive to designers intent rather than close to the computers internal behavior.

Both the statements are the same but the second is preferred.

bookmarks.size == 0
bookmarks.empty?

Ask an array if it has any elements. Don’t check if it has a non-zero size. for the inverse of the above statement checking that we have elements, again the second statement is preferred.

bookmarks.size > 0 
bookmarks.any?

Other language might have some thing like:

if (bookmarks.size == 0) {
  # Add first bookmark
}

Ruby

if bookmarks.empty?
  #Add first bookmark
end

I think the ruby actually reads better and conveys what you are actually trying to do, check the array is empty. With duck typing any object could get passed to this as long as it has the empty? method defined, an object might have header information and a payload. If the payload was implemented as an Array the object could map the empty? onto it.

Previous posts arrays and arrays2