code_junkie

Why do ruby setters need “self.” qualification within the class?

Nov 10th, 2011
123
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.83 KB | None | 0 0
  1. #!/usr/bin/ruby
  2.  
  3. class A
  4. def qwerty; @q; end # manual getter
  5. def qwerty=(value); @q = value; end # manual setter, but attr_accessor is same
  6. def asdf; self.qwerty = 4; end # "self." is necessary in ruby?
  7. def xxx; asdf; end # we can invoke nonsetters w/o "self."
  8. def dump; puts "qwerty = #{qwerty}"; end
  9. end
  10.  
  11. a = A.new
  12. a.xxx
  13. a.dump
  14.  
  15. using System;
  16.  
  17. public class A {
  18. public A() {}
  19. int q;
  20. public int qwerty {
  21. get { return q; }
  22. set { q = value; }
  23. }
  24. public void asdf() { qwerty = 4; } // C# setters work w/o "this."
  25. public void xxx() { asdf(); } // are just like other methods
  26. public void dump() { Console.WriteLine("qwerty = {0}", qwerty); }
  27. }
  28.  
  29. public class Test {
  30. public static void Main() {
  31. A a = new A();
  32. a.xxx();
  33. a.dump();
  34. }
  35. }
  36.  
  37. using System;
  38.  
  39. public class A {
  40. public A() {}
  41. public int test { get { return 4; }}
  42. public int useVariable() {
  43. int test = 5;
  44. return test;
  45. }
  46. public int useMethod() {
  47. int test = 5;
  48. return this.test;
  49. }
  50. }
  51.  
  52. public class Test {
  53. public static void Main() {
  54. A a = new A();
  55. Console.WriteLine("{0}", a.useVariable()); // prints 5
  56. Console.WriteLine("{0}", a.useMethod()); // prints 4
  57. }
  58. }
  59.  
  60. qwerty = 4
  61.  
  62. class A
  63. def test
  64. 4
  65. end
  66. def use_variable
  67. test = 5
  68. test
  69. end
  70. def use_method
  71. test = 5
  72. self.test
  73. end
  74. end
  75. a = A.new
  76. a.use_variable # returns 5
  77. a.use_method # returns 4
  78.  
  79. var = expr // assignment
  80. method = expr // setter method invocation
  81.  
  82. var = expr // assignment (new or existing)
  83. // method = expr, disallow setter method invocation without .
  84.  
  85. symbol = expr // push 'symbol=' onto parse tree and decide later
  86. // if local variable is def'd somewhere in scope: assignment
  87. // else if a setter is def'd in scope: invocation
Add Comment
Please, Sign In to add comment