问题描述
我想确保我在正确的场合使用它们,并想知道任何微妙之处.它们似乎以相同的方式运行,即检查对象字段是否已定义,当我通过控制台使用它们时,当我进行谷歌搜索时,网上没有很多信息.谢谢!
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 field has been defined, when I use them via the console and there isn't a whole lot information online when I did a google search. Thanks!
推荐答案
澄清:present?
和 exists?
都不是纯"的ruby——它们都来自 Rails-land.
To clarify: neither present?
nor exists?
are "pure" ruby—they're both from Rails-land.
present?
是对 Object
的 ActiveSupport 扩展.它通常用作测试对象的一般虚假".来自文档:
present?
is an ActiveSupport extension to Object
. It's usually used as a test for an object's general "falsiness". From the documentation:
如果一个对象不是空的?
,它就是present
.如果对象为 false
、空或空白字符串,则该对象为 blank
.
例如:
[ "", " ", false, nil, [], {} ].any?(&:present?)
# => false
存在吗?
exists?
来自 ActiveResource.来自其文档:
exists?
exists?
is from ActiveResource. From its documentation:
断言资源存在,如果找到资源则返回真.
Note.create(:title => 'Hello, world.', :body => 'Nothing more for now...')
Note.exists?(1) # => true
这篇关于使用 .exists? 和 .present 有什么区别?在红宝石?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!