Within a Ruby class definition, what is the scopes of the private keyword in the following scenarios:
class Foo
def bar_public
puts "public"
end
private
def bar_private
puts "private"
end
开发者_StackOverflow中文版 def bar_public_2
puts "another public"
end
end
Does private only act on bar_private? or on bar_public_2 as well?
In your case both bar_private
and bar_public_2
are private.
That is because both methods are "within scope" of the private
keyword.
> f = Foo.new
#<Foo:0xf1c770>
> Foo.new.bar_private
NoMethodError: private method 'bar_private' called for #<Foo:0xf1c770>
> Foo.new.bar_public_2
NoMethodError: private method 'bar_public_2' called for #<Foo:0xf1c770>
Either way, the best way to answer you question is to open IRB and try it out ;-)
If you find it weird that private
is affecting both bar_private
and bar_public_2
, then rather than use private
, use private :bar_private
after defining bar_private
.
精彩评论