【发布时间】:2015-02-06 10:29:44
【问题描述】:
我正在尝试用 ruby 中的 gsub 函数替换字符串中的一些单词,但有时效果很好,在某些情况下会出现此错误?这种格式有什么问题吗
NoMethodError (undefined method `gsub!' for nil:NilClass):
模型.rb
class Test < ActiveRecord::Base
NEW = 1
WAY = 2
DELTA = 3
BODY = {
NEW => "replace this ID1",
WAY => "replace this ID2 and ID3",
DELTA => "replace this ID4"
}
end
another_model.rb
class Check < ActiveRecord::Base
Test::BODY[2].gsub!("ID2", self.id).gsub!("ID3", self.name)
end
【问题讨论】:
-
实际上,您使用 gsub 的字符串有时为零,这就是它抛出错误的原因。
Test::BODY[2]在某些情况下具有 nil 值。 -
@Fietsband -
WAY是一个等于 2 的常数。 -
@broiSatse 嗯哎呀,错过了那部分。删除了我的评论,因为它无关紧要。
标签: ruby-on-rails ruby gsub