开发者

What kind of variable is ARGV in ruby?

From what I have read ARGV should be a constant since it is all uppercase, but I开发者_JAVA技巧 was able to write a quick program that changed one of the values in ARGV without error. So what type of variable is ARGV?

p ARGV
ARGV[0] = "Not the orginal"
p ARGV


ARGV is an array. Keep in mind that "constant" just means that the variable shouldn't be reassigned, not that the object itself can't change. You may be confusing it with the idea of a const object in C++. That is more equivalent to a frozen object in Ruby. (And note that even "constants shouldn't be reassigned" is a weak guarantee in Ruby. Reassigning a constant doesn't fail; it just prints a warning. It is a bad practice, though.)

To illustrate the difference:

ruby-1.9.2-p0 > CONSTANT = [1,2,3]
 => [1, 2, 3] 
ruby-1.9.2-p0 > frozen = [1,2,3].freeze
 => [1, 2, 3] 
ruby-1.9.2-p0 > CONSTANT << 4
 => [1, 2, 3, 4] 
ruby-1.9.2-p0 > frozen << 4
RuntimeError: can't modify frozen array


ARGV is a constant, but it's an Array. Values in a constant array can be freely changed without any warnings, like any usual array element.

irb(main)> ARGV.class
=> Array
irb(main)> QWERTY = [1, 2, 3, 4]
=> [1, 2, 3, 4]
irb(main)> QWERTY[1] = 5
=> 5
irb(main)> QWERTY
=> [1, 5, 3, 4]
irb(main)> QWERTY << 6
=> [1, 5, 3, 4, 6]
irb(main)> QWERTY = 3
(irb): warning: already initialized constant QWERTY
=> 3
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜