Bill Guindon
3/12/2006 2:52:00 AM
On 3/11/06, Dave Burt <dave@burt.id.au> wrote:
> I find Logan's answers accurate and complete, except for one, which is a
> little complicated. Let me add a little to his answer.
>
> John M. Gabriele wrote:
> >> - Python uses _foo, __bar, and __baz__ underscore notation
> >> loosely for private references. Does Ruby have similar
> >> notions of "privacy"?
>
> Logan Capaldo wrote:
> > Method visibility can be controlled via the private, public, and
> > protected key words. You can always get past these of course by use of
> > #instance_eval for instance.
>
> In "foo.bar", bar is always a method, not a variable. What we call
> attributes are methods that behave like attributes. "foo.bar = baz" calls a
> method called bar=. We use attr_accessor, attr_reader and attr_writer to
> create attributes with their own variables. For example, "class Foo;
> attr_accessor :bar; end; foo = Foo.new"
I found this a bit confusing. Maybe....
attr_accessor, attr_reader and attr_writer can be used to create
attributes with their own variables. They can also create the
appropriate set/get methods for those (or other) variables.
Creating variables and methods:
class Foo
attr_accessor :bar
end
f = Foo.new
f.bar = 'test'
puts f.bar
Creating methods only (variable is created when Foo.new is called):
class Foo
attr_accessor :bar
def initialize(bar='')
@bar = bar
end
end
f = Foo.new
f.bar = 'test'
puts f.bar
> So private, public and protected modify methods. We use sigils for non-local
> variables: $global, @instance_variable, and @@class_variable. You can't say
> foo.@bar, and foo.bar bears no necessary relationship with @bar.
>
> Finally, the methods private, public and protected can be used in two ways.
> Without an argument, they modify the visibility of all the methods defined
> after them in the current scope. They can also be fed specific method names
> to modify the visibility of particular methods.
The method names need to passed as symbols:
class Foo
private :bar
end
> Cheers,
> Dave
>
Cheers to you also.
Forgive me, I'm thinking in editor mode.
--
Bill Guindon (aka aGorilla)
The best answer to most questions is "it depends".