18bytes
18bytes

Reputation: 6029

Why ruby constants are changable? What is the difference between variable?

I was learning ruby, and i learnt that ruby constants must start with a Upper case letter (e.g. Myconstant). This will make it a constant, but its value is changeable!

If a constant's value is changeable then why do we need constant, what is the difference between variable then?

Upvotes: 2

Views: 195

Answers (4)

Joshua Cheek
Joshua Cheek

Reputation: 31726

Constants have lexical scoping, whereas methods have dynamic scoping:

class Super
  Constant = "Super::Constant"

  def method
    'Super#method'
  end

  def get_constant
    Constant
  end

  def get_method
    method
  end
end

class Sub < Super
  Constant = 'Sub::Constant'

  def method
    'Sub#method'
  end
end

Super.new.get_constant # => "Super::Constant"
Sub.new.get_constant   # => "Super::Constant"

Super.new.get_method # => "Super#method"
Sub.new.get_method   # => "Sub#method"

And as far as variables, they are inaccessible from the outside. How would you intend to access these?

class Object
  Constant      = 'constant'  
  local_var     = 'local var'
  @instance_var = 'instance var'
  @@class_var   = 'class var' # btw, never use these
end

Also, there's a lot of things you can do in Ruby, but for your own sanity, be wary. I'd recommend against changing constants around, it will likely frustrate your team.

Upvotes: 2

peter
peter

Reputation: 42182

I use this feature sometimes to test out code without otherwise necessary parameters, eg when i run the script from my editor where it is difficult to provide a parameter.

#ARGV[0] = "c:/test.txt"  #in case of testing i remove the first remark sign

Upvotes: 1

andrewdotnich
andrewdotnich

Reputation: 16784

Some reasons:

1) Convention. It's easy to see just from the name of an identifier that it's not supposed to change.

2) Technical. It (probably; someone more knowledgeable than I will probably answer) makes the interpreter simpler.

3) Dynamism is sometimes helpful; in testing, for example, it's possible to redefine things for testing purposes rather than having to stub/proxy everything…

Upvotes: 2

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230286

Ruby lets you shoot yourself in the foot (if you really want to). But, at least in this case, it warns you about it.

ONE = 'one'
ONE = 'two' # !> already initialized constant ONE

Upvotes: 2

Related Questions