Question

In Ruby if i just assign a local variable.

sound = "bang". 

is that a main.sound=("bang") method? if so, where and how is that method "sound=" being defined? or how is that assignment working? if not, what is actually happening?

i know that for a setter method you would say x.sound=("bang"). and you are calling the method "sound=" on the object "x" with the argument "bang". and you are creating an instance variable "sound".

and i can picture all of that. but not when you assign a variable in the "main" object. as far as i know it isn't an instance variable of the Object class... or is it? I'm so confused.

Was it helpful?

Solution

In most programming languages, Ruby included, assignment is a strange beast. It is not a method or function, what it does is associate a name (also called an lvalue since it's left of the assignment) with a value.

Ruby adds the ability to define methods with names ending in = that can be invoked using the assignment syntax.

Attribute accessors are just methods that create other methods that fetch and assign member variables of the class.

So basically there are 3 ways you see assignment:

  • the primitive = operator
  • methods with names ending in =
  • methods generated for you by the attribute accessor (these are methods ending in =)

OTHER TIPS

A variable assignment is just creating a reference to an object, like naming a dog "Spot". The "=" is not calling any method whatsoever.

As @ZachSmith comments, a simple expression such as sound could refer to a local variable named "sound"or a method of selfnamed "sound". To resolve this ambiguity, Ruby treats an identifier as a local variable if it has "seen" a previous assignment to the variable.

is that a main.sound=("bang") method?

No. main.sound="bang" should set instance variable or element of that variable.
With dot(main.sound) you tell object to do some method(in this case sound).

To manage local variables ruby create new scope.

class E
  a = 42

  def give_a
    puts a
  end

  def self.give_a
    puts a
  end
  binding 
end
bin_e = _ # on pry
E.give_a     # error
E.new.give_a # error

Both methods doesn't know about a. After you create your class, a will soon disappear, deleted by garbage collector. However you can get that value using binding method. It save local scope to some place and you can assign it to the variable.

bin.eval "a" # 42

lambdas have scope where they were defined:

local_var_a = 42
lamb = ->{puts local_var_a} 
lamb.call() # 42
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top