What is the difference between using .exists?, and .present? in Ruby?

后端 未结 6 2059
独厮守ぢ
独厮守ぢ 2020-12-08 09:32

I want to make sure I\'m using them for the correct occasion and want to know of any subtleties. They seem to function the same way, which is to check to see if a object fi

6条回答
  •  长情又很酷
    2020-12-08 09:45

    To clarify: neither present? nor exists? are "pure" ruby—they're both from Rails-land.

    present?

    present? is an ActiveSupport extension to Object. It's usually used as a test for an object's general "falsiness". From the documentation:

    An object is present if it’s not blank?. An object is blank if it’s false, empty, or a whitespace string.

    So, for example:

    [ "", " ", false, nil, [], {} ].any?(&:present?)
    # => false
    

    exists?

    exists? is from ActiveResource. From its documentation:

    Asserts the existence of a resource, returning true if the resource is found.

    Note.create(:title => 'Hello, world.', :body => 'Nothing more for now...')
    Note.exists?(1) # => true
    

提交回复
热议问题