Jonathan
Jonathan

Reputation: 1467

Ruby 'unless' keyword

I'm unsure of what the 'unless' does in this piece of code. Looks extremely simple though.

  def self.tips_by_categories
    @categories = {}
    # Build up the possible categories
    Tip.all.each do |tip|
      tip.categories.each do |category|
        @categories[category.name] = [] unless @categories[category.name]
        @categories[category.name].push(tip)
      end
    end
    @categories
  end

Is it @categories[category.name] = [] if @categories[category.name] is any string?

And if it isn't, what will @categories[category.name] end up being as a result (after the statement is executed)?

Upvotes: 2

Views: 771

Answers (1)

David Grayson
David Grayson

Reputation: 87386

The line with the unless on it is equivalent to:

if !@categories[category.name]
  @categories[category.name] = []
end

If @categories[category.name] is nil or false, it changes it to the empty array []. Otherwise, it leaves it alone.

A much better way to have the same effect is to write:

@categories[category.name] ||= []

or to configure your hash table to have a default proc that returns [].

Upvotes: 8

Related Questions