Ruby Issues

Issues with gsub! in Ruby Command Line Arguments (ARGV)

Shou Arisaka
1 min read
Nov 13, 2025

When you try to use gsub!, you get this error:

/mnt/c/pg/dev.rb:3:in `gsub!': can't modify frozen String (RuntimeError)
        from /mnt/c/pg/dev.rb:3:in `<main>'

This is what I want to do:

s = ARGV[0]
puts s.gsub!(/./,"hoge")

At first I panicked, but it can be easily resolved. It's simply that destructive methods cannot directly modify constants.

In other words, like this:

s = ARGV[0]
puts s.gsub(/./,"hoge")

Let's dig a bit deeper.

“I’m so used to using gsub! that changing everything to gsub is tedious… Oh, can’t I just assign it normally?”

Unfortunately, that doesn't work.

argv = ARGV[0]
# s = argv

So what do you do?

Perform a replacement operation once.

argv = ARGV[0]
s = argv.gsub(//,'')

This works.

Share this article

Shou Arisaka Nov 13, 2025

🔗 Copy Links