Ruby treatment of method defs

In the ruby language if I do this:

def g=( value )
@gval = value.to_s
end

def g
@gval
end

g = 12

Then g == 12, @gval == nil and g.class == Fixnum

I realize that this has to do with the way Ruby processes undefined
identifiers at runtime. However, it strikes me that it is fundamentally
wrong to ignore an existing explicit method declaration within the
current scope in favour of creating a locally scoped variable instead.
This behaviour is counter-intuitive and the ugly work-around required
(self.g = 12) only accentuates how out of place it is.

I presume that there exists a strong reason why this construct remains
in the language. However, I have not been able to find an explanation
as to why this behaviour is desired so if someone here could inform me
as to why it is retained then I would be much obliged.

On Jan 26, 2011, at 12:33 , James B. wrote:

g = 12

Then g == 12, @gval == nil and g.class == Fixnum

I realize that this has to do with the way Ruby processes undefined
identifiers at runtime. However, it strikes me that it is fundamentally
wrong to ignore an existing explicit method declaration within the
current scope in favour of creating a locally scoped variable instead.
This behaviour is counter-intuitive and the ugly work-around required
(self.g = 12) only accentuates how out of place it is.

def x
  g = 12
end

g= is “in scope” as you put it. Which should it be? local assignment or
method call?

require 'g'

def x
  g = 12
end

how about now?

Does your answer change? If so, why?

James B. wrote in post #977707:

I presume that there exists a strong reason why this construct remains
in the language. However, I have not been able to find an explanation
as to why this behaviour is desired so if someone here could inform me
as to why it is retained then I would be much obliged.

Here is one recent explanation:
http://www.ruby-forum.com/topic/941686#977592

g = 123 is an assignment to a local variable. (Local variables are not
objects; they are slots on the stack frame, which hold references to
objects)

foo.g = 123 is syntactic sugar for a method call. The method’s name is
“g=” and the argument is 123. It’s the same as foo.send(:g=, 123)

A bareword “g”, such as in “puts g”, could be either a local variable or
a method call. The choice is made at parse time, which is before run
time.

What this gives you is uncluttered syntax with efficiency. There’s no
need to declare g as a variable, nor do you need to use parentheses to
call function f(). But because the distinction is made ahead-of-time, it
doesn’t have to be decided every time the code is executed in a loop.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs