Class initialization with assignment-like method

I'm trying to understand this:

module A
  def a=(num)
    @a = num % 2
  end

  def b(num)
    @b = num % 2
  end
end

class B
  include A
  def initialize(num)
    a = num
    b(num)
  end
end

class C
  include A
  def initialize(num)
    self.a = num
    self.b(num)
  end
end

b = B.new 10 # => #<B:0x007ffb27497f58 @b=0>
b.instance_variables # => [:@b]
b.a = 10 # => 10
b.instance_variables # => [:@b, :@a]

c = C.new 10 # => #<C:0x007ffb2755e798 @a=0, @b=0>
c.instance_variables # => [:@a, :@b]

Why the "assignment-like" method needs a "self" when the class is
initializated and the others methods don't?

Thanks!
panchiz

···

--
Posted via http://www.ruby-forum.com/.

The interpreter looks at "a = num" and assumes that you're referring to
a local variable "a", rather than the method "a=".

···

--
Posted via http://www.ruby-forum.com/.

I thought that the interpreter should have loaded up all the methods but
seems logic what you are pointing.

Thanks

···

--
Posted via http://www.ruby-forum.com/.

It does not have to do with "loading methods" or such. It is purely
syntactical: the moment the parser sees an assignment without a
qualifier (dot) it parses this as a local variable assignment and the
local variable is known from that line on.

$ ruby -e 'def a;puts "a called"; 99 end;p a; p defined?(a); a=8; p a;
p defined?(a)'
a called
99
"method"
8
"local-variable"

Kind regards

robert

···

On Tue, Dec 10, 2013 at 5:15 PM, panchiz D. <lists@ruby-forum.com> wrote:

I thought that the interpreter should have loaded up all the methods but
seems logic what you are pointing.

--
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/