Explanation of ruby attr_accessor and cattr_accessor

Recommended for you: Get network issues from WhatsUp Gold. Not end users.

1 attr_accessor usage is quite simple, is equivalent to getter and setter, see a class will know what to do with:

Ruby code Copy code

  1. class Test
  2. attr_accessor :name
  3. def initialize()
  4. @name = "yanzilee9292"
  5. end
  6. end
  7. #test
  8. puts Test.new.name

class Test
  attr_accessor :name
  def initialize()
	@name = "yanzilee9292"

puts Test.new.name

Save this class for the test.rb file, through the command line to run ruby test.rb, get the following results:


2 if we drop the attr_accessor, how to output the name value

Java code Copy code

  1. class Test
  2. def initialize()
  3. @name ="yanzilee9292"
  4. end
  5. #test
  6. puts Test.new.instance_eval {@name}
  7. end

class Test
  def initialize()
	@name ="yanzilee9292"
  puts Test.new.instance_eval {@name}

As you can see, attr_accessor will make things easier

3 the difference between cattr_accessor and attr_accessor

Cattr_accessor is a static class variable is equal to the Java, sharing on all instances

Ruby code Copy code

  1. class Counter
  2. cattr_accessor :class_count
  3. attr_accessor :instance_count
  4. end
  5. counter1 = Counter.new
  6. counter1.instance_count = 1
  7. counter1.class_count = 1
  8. counter2 = Counter.new
  9. p counter2.instance_count
  10. #> nil
  11. p counter2.class_count
  12. #> 1
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download

Posted by Beau at January 21, 2014 - 4:09 PM