為什么Ruby設置者需要“Self”班里的資格?Ruby setter-是否由(c)attr_accessor或者手動-似乎是唯一需要的方法self.在類本身內訪問時的限定條件。這似乎使Ruby單獨進入了語言世界:所有方法都需要self/this(比如Perl,我認為Javascript)不需要任何方法self/thisIS(C#,Java)只有策劃者才需要self/this(紅寶石?)最好的比較是C#與Ruby,因為兩種語言都支持語法上像類實例變量一樣工作的訪問器方法:foo.x = y, y = foo.x..C#稱它們為屬性。下面是一個簡單的例子;Ruby中的同一個程序,然后是C#:class A def qwerty; @q; end # manual getter
def qwerty=(value); @q = value; end # manual setter, but attr_accessor is same
def asdf; self.qwerty = 4; end # "self." is necessary in ruby?
def xxx; asdf; end # we can invoke nonsetters w/o "self."
def dump; puts "qwerty = #{qwerty}"; endenda = A.new
a.xxx
a.dump拿走self.qwerty =()并且失敗了(Linux&OSX上的Ruby1.8.6)?,F在C#:using System;public class A {
public A() {}
int q;
public int qwerty {
get { return q; }
set { q = value; }
}
public void asdf() { qwerty = 4; } // C# setters work w/o "this."
public void xxx() { asdf(); } // are just like other methods
public void dump() { Console.WriteLine("qwerty = {0}", qwerty); }}public class Test {
public static void Main() {
A a = new A();
a.xxx();
a.dump();
}}問:這是真的嗎?除了策劃人以外,還有其他需要自我的場合嗎?也就是說,在其他情況下,Ruby方法不可能被調用無賽爾夫?當然,在很多情況下,賽爾夫成是必要的。這并不是Ruby獨有的,只是要明確一點:using System;public class A {
public A() {}
public int test { get { return 4; }}
public int useVariable() {
int test = 5;
return test;
}
public int useMethod() {
int test = 5;
return this.test;
}}public class Test {
public static void Main() {
A a = new A();
Console.WriteLine("{0}", a.useVariable()); // prints 5
Console.WriteLine("{0}", a.useMethod()); // prints 4
}}同樣的歧義是以同樣的方式解決的。但我想問的是這個案子一種方法有被定義,和不已經定義了局部變量,并且我們遇到qwerty = 4這是一個方法調用還是一個新的局部變量賦值?
3 回答

慕斯王
TA貢獻1864條經驗 獲得超2個贊
qwerty = 4
qwerty
self.
self.
:
class A def test 4 end def use_variable test = 5 test end def use_method test = 5 self.test endenda = A.new a.use_variable # returns 5a.use_method # returns 4
test
self.
this.
- 3 回答
- 0 關注
- 532 瀏覽
添加回答
舉報
0/150
提交
取消