Rather than
str.downcase!
str.gsub!(/\W/, "")
it seems that I should be able to use multiple destructive String methods in succession:
str.downcase!.gsub!(/W/, "")
Sometimes this works, but sometimes it causes an error.
irb(main):001:0> str = "Foobar!"
"Foobar!"
irb(main):002:0> str.downcase!.gsub!(/\W/, "")
"foobar"
irb(main):003:0> str
"foobar"
irb(main):004:0> str.downcase!.gsub!(/\W/, "")
NoMethodError: undefined method `gsub!' for nil:NilClass
from (irb):4
from /usr/bin/irb:12:in `<main>'
Why is this?
Many destructive methods, including
gsub, returnnilif they don’t change anything. So it’s usually not a good idea to chain them. Instead useor