Replace a word using gsub function in ruby

I am trying to replace a word from a string with the gsub function in ruby, but sometimes it works fine and in some cases gives this error? are there any problems with this format

NoMethodError (undefined method `gsub!' for nil:NilClass):   

model.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
+4
source share
2 answers

Ah, I found it! gsub!- a very strange method. First, it replaces the string in place, so it actually modifies your string. Secondly, it returns nilwhen no replacement has been made. All this adds up to the error you receive.

, , , , "replace this 3 and name". , gsub , , . gsub .

, - , . ( ). , gsub (no bang). , .

+4

, , . Interpolation.

class Test < ActiveRecord::Base
  # Here use symbols instead, because symbols themselfs are immutable
  # so :way will always equal :way
  BODY = {
    :new => "replace this %{ID1}",
    :way => "replace this %{ID2} and %{ID3}",
    :delta => "replace this %{ID4}"
  }    
end
# HERE you should create another constant based on the 
# Test class constants
class Check < ActiveRecord::Base
  BODY = {
         :way => Test::BODY[:way] % {ID2: self.id, ID3: self.name}
  }

 # Or you can make it a method
 def self.body
   Test::BODY[:way] % {ID2: self.id, ID3: self.name}
 end
end

-

:

str = "%{num1} / %{num1} = 1"
str % {num1: 3} # 3 / 3 = 1

@BroiSatse , , .

+2

All Articles