问题描述
所以我知道 bang(感叹号)和非 bang 方法之间的区别通常是该方法是否会修改对象本身或返回一个单独的修改对象,保持原始不变.
So I know the distinction between the bang (exclamation mark) and non-bang methods usually is whether the method will modify the object itself or return a separate modified object keeping the original unchanged.
然后,在本书第 6 章中构建 User 模型时,我遇到了 User.create
方法,该方法可以创建一个新模型并将其保存到数据库中,只需一个步骤.在 Michael Hartl 的 Ruby on Rails 3 教程 中,他写道 User.create!
方法就像 create
方法一样......除了如果创建失败,它会引发 ActiveRecord::Record-Invalid 异常."
Then while building the User model in chapter 6 of the book, I came across the User.create
method, which creates a new model and saves it to the database in a single step. In Michael Hartl's Ruby on Rails 3 Tutorial, he writes that the User.create!
method "works just like the create
method...except that it raises an ActiveRecord::Record-Invalid exception if the creation fails."
我很困惑.User.create!
方法是不是不遵循 Ruby 的bang-convention",还是我完全遗漏了什么?如果他遵循约定,User.create!
如果是类方法,如何修改self?
I'm pretty confused. Is the User.create!
method not following Ruby "bang-convention" or am I completely missing something? And if he IS following the convention, how does User.create!
modify self if it is a class method?
推荐答案
虽然很多类将 bang 方法视为一种在适当位置修改对象的方法",但我喜欢 更好:
Though a lot of classes treat bang methods as "a method that modifies the object in place", I like the description of bang methods from the Eloquent Ruby book better:
在实践中,Ruby 程序员保留!装饰方法的名称出乎意料的事情,或者有点危险
因此,在这种情况下,意外"结果是引发异常,而不仅仅是失败并返回 false
.
So in this case, the "unexpected" result is that an exception is raised instead of just failing and returning false
.
这篇关于Rails——创造和创造!方法,RoR 3 教程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!