Understand self for the class method attr_accessor

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 myself as a test itself, but did not return a result some_data.

But so far I have changed as follows, it returns the expected result

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 are the differences?

EDIT

Now in the first example, if I set the get method someas

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

Now it has made me much more confused.

+5
source share
5 answers

some = :foomakes ruby ​​think he should create a new local variable with the name some. If you want to call some=(), you need to use an explicit receiver - as in self.some = :foo. I once lost a bet on that ...: - /

+10
source

()

+1

some - .

, some self. ? attr_accessor :some :

def some= (val)
  @some = val
end

def some
  return @some
end

, getter setter @some ( Test, Class).

0

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

some - .. , @some, ( ), , .

setter some @some -,

@some = 'some_data'

self.some = 'some_data'

def get_some
  puts self.inspect
  self.some
end

-. instace @some.. @some .. nil..

0

1

class Foo
  def initialize
    @foo = 'foo'
  end

  def print_foo
    print @foo
    print self.foo
    print foo
  end
end

@foo, self.foo foo @foo :

Foo.new.print_foo # = > foofoofoo

2

class Foo
  def initialize
    @foo = 'foo'
  end

  def foo
    return 'bar'
  end

  def print_foo
    print @foo
    print self.foo
    print foo
  end
end

@foo , self.foo foo foo:

Foo.new.print_foo # = > foobarbar

3

class Foo
  def initialize
    @foo = 'foo'
  end

  def foo
    return 'bar'
  end

  def print_foo
    foo = 'baz'
    print @foo
    print self.foo
    print foo
  end
end

@foo , self.foo foo :

Foo.new.print_foo # = > foobarbaz

0

All Articles