gpt4 book ai didi

ruby-on-rails - 使用 .exists? 和 .present 有什么区别?在 ruby ?

转载 作者:数据小太阳 更新时间:2023-10-29 06:21:37 24 4
gpt4 key购买 nike

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

最佳答案

澄清一下:present?exists? 都不是“纯”ruby — 它们都来自 Rails-land。

现在?

present?Object 的 ActiveSupport 扩展。它通常用作对对象的一般“虚假性”的测试。来自 the documentation :

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。来自 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

关于ruby-on-rails - 使用 .exists? 和 .present 有什么区别?在 ruby ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13186722/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com