[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Information Hiding

arcadio

11/9/2007 4:48:00 PM

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

3 Answers

Robert Klemme

11/9/2007 5:42:00 PM

0

2007/11/9, arcadiorubiogarcia@gmail.com <arcadiorubiogarcia@gmail.com>:
> 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

--
use.inject do |as, often| as.you_can - without end

Ryan Davis

11/9/2007 6:07:00 PM

0


On Nov 9, 2007, at 09:41 , Robert Klemme wrote:

> 2007/11/9, arcadiorubiogarcia@gmail.com
> <arcadiorubiogarcia@gmail.com>:
>> a return nil? def bar(p); @a << p; return nil; end
>
> In this case I'd do
>
> def bar(x)
> @a << x
> self
> end

Follow this advice.

> use.inject do |as, often| as.you_can - without end

Ignore this advice.



arcadio

11/9/2007 8:38:00 PM

0

Ok, thanks a lot for the tips.

On 9 nov, 19:07, Ryan Davis <ryand-r...@zenspider.com> wrote:
> On Nov 9, 2007, at 09:41 , Robert Klemme wrote:
>
> > 2007/11/9, arcadiorubiogar...@gmail.com
> > <arcadiorubiogar...@gmail.com>:
> >> a return nil? def bar(p); @a << p; return nil; end
>
> > In this case I'd do
>
> > def bar(x)
> > @a << x
> > self
> > end
>
> Follow this advice.
>
> > use.inject do |as, often| as.you_can - without end
>
> Ignore this advice.