【问题标题】:what does an exclamation mark follow with variable mean in ruby on rails? [duplicate]在 ruby​​ on rails 中,感叹号后面是什么意思? [复制]
【发布时间】:2011-09-09 18:33:02
【问题描述】:

可能重复:
Why are exclamation marks used in Ruby methods?

我正在阅读使用 MongoDB 的 Rails3 教程

http://www.mongodb.org/display/DOCS/MongoDB+Data+Modeling+and+Rails

我看到了 键:user_id,ObjectId 时间戳! 感叹号是什么意思??

谢谢。

 class Story
  include MongoMapper::Document

  key :title,     String
  key :url,       String
  key :slug,      String
  key :voters,    Array
  key :votes,     Integer, :default => 0
  key :relevance, Integer, :default => 0

  # Cached values.
  key :comment_count, Integer, :default => 0
  key :username,      String

  # Note this: ids are of class ObjectId.
  key :user_id,   ObjectId
  timestamps!

  # Relationships.
  belongs_to :user

  # Validations.
  validates_presence_of :title, :url, :user_id
end

【问题讨论】:

标签: ruby ruby-on-rails-3 mongomapper


【解决方案1】:

一般来说,当 Ruby 中的方法跟在一个“bang”之后时,它会更改源代码。

例如查看以下输出:

irb(main):007:0> x = 'string'
=> "string"
irb(main):008:0> x
=> "string"
irb(main):009:0> x.capitalize
=> "String"
irb(main):010:0> x
=> "string"
irb(main):011:0> x.capitalize!
=> "String"
irb(main):012:0> x
=> "String"

x.capitalize 返回“字符串”,但变量 x 保持小写。当我添加! ('bang') 到最后 var x 被修改。

我对 mongodb 不是很熟悉,但这可能会对 ruby​​ 中爆炸的目的有所了解。

【讨论】:

  • 这里只是说明一下,破坏性方法(即更改源)中使用的 bang 只是一种约定——而 Ruby 充满了约定。
  • 谢谢,我是一个全新的 ruby​​ 新手,但我喜欢理解这样的问题。所以我昨晚花了一些时间,知道这个话题可能会被关闭。感谢您清除它! +1
猜你喜欢
  • 2011-09-09
  • 2018-05-22
  • 2018-01-05
  • 2021-09-18
  • 2011-01-11
  • 2011-11-19
  • 2016-05-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多