开发者

Equivalent ruby code to following without attr_accessor?

This is a Java Code :

public class test{
     public static void main(String args[]){
   开发者_开发问答  number A = new number();
     System.out.println(A.b);       
    }   
}

class number{
    int b = 100;    
}

Is there a equivalent of above code in ruby without attr_accessor ?

Why can't we access member variables using '.' like in java ? or is there a way i am unaware of in ruby ... ?


Instance variables are hidden by default. You can get around this by using instance_variable_get and instance_variable_set, but these are private (you can get around this too if you must) because it's unidiomatic to do such things.

In Ruby, when you say foo.bar, you are invoking the bar method on your foo object (with no arguments). When you say foo.bar = 5, you are invoking the bar= method with argument 5.

All attr_accessor does is provide implementations of bar and bar= for you, but this:

class MyClass
  attr_accessor :bar
end

is equivalent to

class MyClass
  def bar
    @bar
  end

  def bar=(new_bar)
    @bar = new_bar
  end
end

This lets you later replace the implementation with something else if you wish. Instance variables are supposed to be private to that object, so I wouldn't recommend trying to work around this unless you're doing heavy-duty metaprogramming.


If you just want to pass around structured data, then you can use the Ruby Struct class, which will work more like you'd expect from your example:

Number = Struct.new(:value)
n = Number.new
n.value = 123
n.value # => 123


The equivalent is using Ruby's attr_accessor. Why do you want to avoid it?

class number
  attr_accessor :b
end

Then you can call

a = number.new
a.b = 1
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜