# Public/private/protected instead of def

**URL:** <https://www.ruby-forum.com/t/public-private-protected-instead-of-def/186407>\
**Category:** Ruby\
**Created:** [April 6, 2010, 5:35pm UTC](https://www.ruby-forum.com/t/public-private-protected-instead-of-def/186407 "2010-04-06T17:35:27Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![tcsnide](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/t/eb8c5e/32.png) [@tcsnide](https://www.ruby-forum.com/u/tcsnide)\
**Post date:** [April 6, 2010, 5:35pm UTC](https://www.ruby-forum.com/t/public-private-protected-instead-of-def/186407/1 "2010-04-06T17:35:27Z")

</div>

First of all, I am curious. Is there any way to do the following but  
still retain backward compatibility?

class Module  
# unfortunately super doesn’t work  
alias :publicize :public  
alias :privatize :private  
alias :protect :protected

```
def public(name, &code)
  define_method(name, &code) if code
  publicize(name)
end

def private(name, &code)
  define_method(name, &code) if code
  privatize(name)
end

def protected(name, &code)
  define_method(name, &code) if code
  protect(name)
end

```

end

Example

class X

```
public :x do |*a|
  p a
end

private :y do |*a|
  p a
end

protected :z do |*a|
  p a
end

```

end

Secondly, I guess ‘def’ was just nice because of it’s uniformity  
throughout modules and classes, but I have to wonder if the more Java  
like to use of public/private/protected might ultimately be a bit more  
beneficial (especially if they could be generalized to allow the  
definition of others via meta-programming). Classes might look more  
like:

class X

```
public_accessor :a

private_reader :b

protected_writer :c

public x(*a)
  p a
end

private y(*a)
  p a
end

protected z(*a)
  p a
end

```

end

---

<div class="post-metadata">

**Author:** ![tcsnide](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/t/eb8c5e/32.png) [@tcsnide](https://www.ruby-forum.com/u/tcsnide)\
**Post date:** [April 6, 2010, 6:21pm UTC](https://www.ruby-forum.com/t/public-private-protected-instead-of-def/186407/2 "2010-04-06T18:21:42Z")

</div>

I should point out why this even crossed my mind. I have a piece of  
code like so:

class C \< Module  
def initialize(&block)  
instance\_eval(&block)  
end  
end

Within it the normal public/private/protected do not work.

M = C.new do  
private  
define\_method(:x){ “x” }  
end

class X  
include M  
end

X.new.x #=\> “x” (instead of an error)

So it occurred to to make public/private/protected helper methods in  
this context, which led me to the larger thought.
