[#97678] [Ruby master Feature#16752] :private param for const_set — bughitgithub@...
Issue #16752 has been reported by bughit (bug hit).
5 messages
2020/04/02
[ruby-core:97872] [Ruby master Feature#16783] Implicit vs explicit self
From:
merch-redmine@...
Date:
2020-04-13 17:59:28 UTC
List:
ruby-core #97872
Issue #16783 has been updated by jeremyevans0 (Jeremy Evans).
Status changed from Open to Closed
This was implemented in Ruby 2.7:
```ruby
class A
def b
self.a
self.a = 1
end
private
attr_accessor :a
end
p A.new.b
# 2.7: 1
# 2.6 and below: NoMethodError
```
See #11297 and #16123.
----------------------------------------
Feature #16783: Implicit vs explicit self
https://bugs.ruby-lang.org/issues/16783#change-85095
* Author: koriroys (Kori Roys)
* Status: Closed
* 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"
# should this work?
thing.public_getter_calling_private_getter_with_explicit_self # => NoMethodError (private method `private_name' called for Thing)
```
--
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>