3

This does not output anything:

class Test

  attr_accessor :value

  def run
    set_value
    puts value
  end

  def set_value
    value = 6 # No 'self'
  end
end

Test.new.run

Whereas this outputs '6'

class Test

  attr_accessor :value

  def run
    set_value
    puts value
  end

  def set_value
    self.value = 6 # With 'self'
  end
end

Test.new.run

Why do I need self when the method is defined already? Surely Ruby should use the method rather than creating a local variable in the set_value function?

Matt Gibson
  • 14,105
  • 7
  • 50
  • 77

3 Answers3

7

Why do I need self when the method is defined already?

Assignment Methods

When using method assignment you must always have a receiver. If you do not have a receiver Ruby assumes you are assigning to a local variable

Arup Rakshit
  • 113,563
  • 27
  • 250
  • 306
2

You have to create an instance variable with the '@' character :

value = 6 # create a local variable 'value' and set it to 6

@value = 6 # create an instance variable named 'value' and set it to 6, it will be accessible through the accessor #value

EDIT

self.value = 6 

calls the method #value=(new_value), implicitly declared from attr_accessor, which sets the @value instance variable to new_value (possible from other scopes)

@value = 6

directly sets the instance variable to 6 (only possible from instance scope)

floum
  • 1,139
  • 6
  • 17
0

You always need to use self so ruby can know if you're not instantiating a new variable:

self.value = 6 #ruby knows it's your class variable

value = 6 #ruby thinks you're creating a new variable called value

Assignment Methods

lcguida
  • 3,667
  • 2
  • 30
  • 54