Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

understand self for attr_accessor class method

class Test
  class << self
    attr_accessor :some

    def set_some
      puts self.inspect
      some = 'some_data'
    end
    def get_some
      puts self.inspect
      some
    end
  end
end

Test.set_some => Test
puts Test.get_some.inspect => Test nil

Here above I could find self as Test itself but not returning the some_data as output.

But while I modified in following way it returns expected output

class Test
  class << self
    attr_accessor :some

    def set_some
      puts self.inspect
      self.some = 'some_data'
    end
    def get_some
      puts self.inspect
      self.some
    end
  end
end

Test.set_some => Test
puts Test.get_some.inspect => Test some_data

What is the differences?

EDIT

Now in the first example if I set as get some method as

Test.some = 'new_data'
puts Test.some.inspect #=> new_data
Test.set_some
puts Test.get_some.inspect => new_data

Now it made me much more confused.

like image 974
kriysna Avatar asked May 11 '11 10:05

kriysna


People also ask

Is attr_accessor a method?

attr_accessor is a shortcut method when you need both attr_reader and attr_writer . Since both reading and writing data are common, the idiomatic method attr_accessor is quite useful.

What is self method in Ruby?

self is a special variable that points to the object that "owns" the currently executing code. Ruby uses self everwhere: For instance variables: @myvar. For method and constant lookup. When defining methods, classes and modules.

What does attr_accessor do in Rails?

attr_accessor is used to define an attribute for object of Model which is not mapped with any column in database.

What is attr_reader?

We use this when we need a variable that should only be changed from private methods, but whose value still needs to be available publicly. The attr_reader method takes the names of the object's attributes as arguments and automatically creates getter methods for each.


1 Answers

some = :foo makes ruby think it should create a new local variable with name some. If you want to call some=(), you have to use an explicit reciever - as in self.some = :foo. I once lost a bet on that... :-/

like image 185
Reactormonk Avatar answered Sep 30 '22 11:09

Reactormonk