使用 .exists? 和 .present 有什么区别?在红宝石? [英] What is the difference between using .exists?, and .present? in Ruby?

查看:27
本文介绍了使用 .exists? 和 .present 有什么区别?在红宝石?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想确保我在正确的场合使用它们,并想知道任何微妙之处.它们似乎以相同的方式运行,即检查对象字段是否已定义,当我通过控制台使用它们时,当我进行谷歌搜索时,网上没有很多信息.谢谢!

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.

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

例如:

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

存在吗?

exists? 来自 ActiveResource.来自其文档:

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

这篇关于使用 .exists? 和 .present 有什么区别?在红宝石?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆