Blankman
Blankman

Reputation: 267330

How can I override this Ruby variable?

The original code looks like this:

module Acme
  class Address
    STREET_NAME = "123 acme inc drive".freeze

    ..
    ..
  end
end

This is a 3rd party gem, I was hoping I could modify the STREET_NAME variable in a initializer somehow, without having to edit the source code. Is this possible?

Upvotes: 2

Views: 119

Answers (1)

Andrew Marshall
Andrew Marshall

Reputation: 97014

Just reassign it:

Acme::Address::STREET_NAME = "1 Infinite Loop"

Freezing an object freezes just that: the object, not the variable (reference) itself. Reassigning a constant will give you a warning though:

warning: already initialized constant STREET_NAME

since it's generally not a good idea to reassign a constant—but this is Ruby, and since everything is dynamic, constants aren't really constant. Doing this in an initializer should work just fine.

Upvotes: 9

Related Questions