NikitaShrestha
NikitaShrestha

Reputation: 39

ARGV in Ruby: The Meaning of a Constant

I am new to Ruby, so please bear my questions in case they might not make any sense. My question is,

A constant is where we assign values that should not be altered. Why is ARGV a constant, when we can pass as many arguments as we want to in it? Are the arguments not the values for ARGV? When we pass arguments to ARGV, are we assigning values or does ARGV already have its own sets of values?

Upvotes: 0

Views: 563

Answers (3)

sawa
sawa

Reputation: 168249

A constant has to have its value newly assigned at some point. If you take the meaning of constant as something that is never newly assigned its value, then there would be no constant at all. A constant is therefore, a relative notion; you cannot define what a constant is without the relevant domain/scope. A constant remains consistant within that domain, but has its value assigned/changed outside of the scope.

In mathematics, suppose some mathematician used a constant A = 3 at some point in their life solving a certain problem. That does not mean that everyone from that point on using the constant A would always have to assume its value to be 3. In mathematics, the domain of a constant can be a single proof, an article, a book, or a convention throughout a subfield, etc.

For a computer program, the domain for a constant is usually the execution lifespan of a program. A constant remains constant relative to the execution of the program. ARGV has its values set prior to the execution of the Ruby program.

Upvotes: 3

CDub
CDub

Reputation: 13354

ARGV is a constant array that is defined on initialization of a Ruby script, in which the values in that array are set to the arguments which were passed in to the script itself.

From the ARGF documentation:

ARGF is a stream designed for use in scripts that process files given as command-line arguments or passed in via STDIN.

The arguments passed to your script are stored in the ARGV Array, one argument per element. ARGF assumes that any arguments that aren't filenames have been removed from ARGV

See the documentation for ARGV for more details.

Upvotes: 2

Patrick Oscity
Patrick Oscity

Reputation: 54734

The point is that ARGV has constant value for the entire time span your program runs. Another reason is that you are not supposed to change the value of ARGV. From the Wikipedia page titled Constant (computer programming):

[…] a constant is an identifier whose associated value cannot typically be altered by the program during its execution […]

Ruby is a bit special because it allows you to reassign ARGV (as any other constant), although it will issue a warning. The following is valid Ruby code (but please don’t do this):

ARGV = [123]
# warning: already initialized constant ARGV

p ARGV
# [123]

Upvotes: 3

Related Questions