Syntactic Sugar For Empty Containers
Join the DZone community and get the full member experience.Join For Free
In any web application, we're often just reading a collection of rows from the database and displaying it in the browser. Often times, we'll have code that looks like this:
unless @friends.empty? @friends.each do |friend| puts friend.username end else puts No friends yet enddunno why, but I find this kinda ugly. Can we do better?
@friends.each do |friend| puts friend.username end.empty do puts No friends yet endWell, that worked. I kinda like it. In a way, it's almost like being able to write my own "else" statement. If I had used curly braces instead of "do/end", it might look pretty close. Here's the code for empty:
class Array def empty(message = "") if self.empty? return block_given? ? (yield message) : message end end endYou can read the full post at: http://webjazz.blogspot.com/2007/09/syntactic-sugar-for-dealing-with-empty.html
Opinions expressed by DZone contributors are their own.