Information Hiding

  • Thread starter arcadiorubiogarcia
  • Start date
A

arcadiorubiogarcia

Hi,

I'm quite new to Ruby, so please excuse me if this question is a bit
silly.

Consider:

class Foo
def initialize
@a = []
end

def bar(p)
@a << p
end
end

It's nice that Ruby returns the last evaluated expression, without
putting an explicit return. However, Foo#bar dangerously exposes the
Foo class internals.

My question is, what is the common idiom to avoid this? Simply adding
a return nil? def bar(p); @a << p; return nil; end

Thanks in advance
 
R

Robert Klemme

2007/11/9 said:
Hi,

I'm quite new to Ruby, so please excuse me if this question is a bit
silly.

Consider:

class Foo
def initialize
@a = []
end

def bar(p)
@a << p
end
end

It's nice that Ruby returns the last evaluated expression, without
putting an explicit return. However, Foo#bar dangerously exposes the
Foo class internals.

My question is, what is the common idiom to avoid this? Simply adding
a return nil? def bar(p); @a << p; return nil; end

In this case I'd do

def bar(x)
@a << x
self
end

Because then you can nicely chain calls to #bar. Depending on
circumstances you might even consider implementing #<< instead of /
additionally to #bar.

Kind regards

robert
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,270
Messages
2,571,351
Members
48,036
Latest member
nickwillsonn

Latest Threads

Top