Issue #16783 has been reported by koriroys (Kori Roys).

----------------------------------------
Feature #16783: Implicit vs explicit self
https://bugs.ruby-lang.org/issues/16783

* Author: koriroys (Kori Roys)
* Status: Open
* Priority: Normal
----------------------------------------
I recently ran into this case while trying to explain why `self` is needed for calling setters (can't disambiguate between creating a local variable versus calling the setter because of the syntactic sugar). However, I couldn't come up with a good reason why `self` throws an error when calling private getters. It feels inconsistent? I think it would be more consistent to be able to specify `self.private_getter` and `self.private_setter = "value"`, though I don't know the implications. Would this be possible? Would people appreciate this?

``` ruby
class Thing

  # works
  def public_method_calling_private_setter_with_explicit_self
    self.name = "value"
  end
  
  # works, but doesn't call the private setter
  # common beginner mistake
  def public_method_creating_local_variable
    name = "whoops!"
  end
  
  # works
  def public_getter_accessing_instance_variable
    @name
  end
  
  # works
  def public_getter_calling_private_getter_with_implicit_self
    private_name
  end

  # DOES NOT work
  def public_getter_calling_private_getter_with_explicit_self
    self.private_name
  end

  private
  def name=(value)
    @name = value
  end
  
  def private_name
    @name
  end
end

thing = Thing.new
thing.public_getter_accessing_instance_variable #=> nil
thing.public_method_calling_private_setter_with_explicit_self # => "value"
thing.public_getter_accessing_instance_variable #=> "value"

thing.public_method_creating_local_variable # => "whoops!"
# instance variable unchanged
thing.public_getter_accessing_instance_variable # => "value"

thing.public_getter_calling_private_getter_with_implicit_self # => "value"

# this following method should work
thing.public_getter_calling_private_getter_with_explicit_self # => NoMethodError (private method `private_name' called for Thing4)
```




-- 
https://bugs.ruby-lang.org/

Unsubscribe: <mailto:ruby-core-request / ruby-lang.org?subject=unsubscribe>
<http://lists.ruby-lang.org/cgi-bin/mailman/options/ruby-core>