M
minkoo.seo
Hi, all.
I'm a somewhat newbie in ruby realm, and trying to write some codes.
Yesterday, I've found very strange characteristics in ruby.
Please see the following:
irb(main):001:0> class Foo
irb(main):002:1> private
irb(main):003:1> def bar
irb(main):004:2> print "hi"
irb(main):005:2> end
irb(main):006:1> end
=> nil
irb(main):007:0> class Foo
irb(main):008:1> public
irb(main):009:1> def duh
irb(main):010:2> f = Foo.new
irb(main):011:2> f.bar
irb(main):012:2> end
irb(main):013:1> end
=> nil
irb(main):014:0> f = Foo.new
=> #<Foo:0x2cdd2f0>
irb(main):015:0> f.duh
NoMethodError: private method `bar' called for #<Foo:0x2cdb7a8>
from (irb):11:in `duh'
from (irb):15
irb(main):016:0> quit
As you can see in the above, method "bar" is private to Foo. And that
method is called from another public method "duh". "duh" calls private
method of "f", which is not the instance where "duh" is called.
In all other languages, such as Java and C++, it is perfectly legal to
call private method as long as the method is called from methods of
the same class.
For example, the following complies in C++:
#include <iostream>
using namespace std;
class Foo
{
private:
void foo()
{
cout << "hi" << endl;
}
public:
void duh()
{
Foo f;
f.foo();
}
};
int main()
{
Foo f;
f.duh();
return 0;
}
I'm not saying that Ruby is wrong while the others are correct. I'm
just trying to figure out the "reason" of this strange behavior. Any
one can tell me?
I'm a somewhat newbie in ruby realm, and trying to write some codes.
Yesterday, I've found very strange characteristics in ruby.
Please see the following:
irb(main):001:0> class Foo
irb(main):002:1> private
irb(main):003:1> def bar
irb(main):004:2> print "hi"
irb(main):005:2> end
irb(main):006:1> end
=> nil
irb(main):007:0> class Foo
irb(main):008:1> public
irb(main):009:1> def duh
irb(main):010:2> f = Foo.new
irb(main):011:2> f.bar
irb(main):012:2> end
irb(main):013:1> end
=> nil
irb(main):014:0> f = Foo.new
=> #<Foo:0x2cdd2f0>
irb(main):015:0> f.duh
NoMethodError: private method `bar' called for #<Foo:0x2cdb7a8>
from (irb):11:in `duh'
from (irb):15
irb(main):016:0> quit
As you can see in the above, method "bar" is private to Foo. And that
method is called from another public method "duh". "duh" calls private
method of "f", which is not the instance where "duh" is called.
In all other languages, such as Java and C++, it is perfectly legal to
call private method as long as the method is called from methods of
the same class.
For example, the following complies in C++:
#include <iostream>
using namespace std;
class Foo
{
private:
void foo()
{
cout << "hi" << endl;
}
public:
void duh()
{
Foo f;
f.foo();
}
};
int main()
{
Foo f;
f.duh();
return 0;
}
I'm not saying that Ruby is wrong while the others are correct. I'm
just trying to figure out the "reason" of this strange behavior. Any
one can tell me?