获取空数组的第一个元素

Getting the first element of an empty Array

给定一个包含零个或一个元素的数组,我如何 return 第一个元素或 nil?

我有工作代码,但不是很优雅:

class Category < ActiveRecord::Model
  adapter sqlite

  table_name "categories"

  primary id      : Int
  field parent_id : Int
  field name      : String

  # return a category or nil
  def self.root
    roots = where(criteria("parent_id").is_null)

    if roots.empty?
      nil
    else
      roots.first
    end⋅
  end
end

您可以简单地在数组上调用 first?

  def self.root
    where(criteria("parent_id").is_null).first?
  end