简体   繁体   中英

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)?

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 [] .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM