attr_accessor aur Encapsulation
Har instance variable ke liye haath se getter aur setter likhna mechanical aur repetitive hai: def x; @x; end aur def x=(value); @x = value; end, over and over. attr_accessor :x ek line mein dono methods aapke liye generate karta hai. attr_reader sirf getter generate karta hai (bahar se read-only); attr_writer sirf setter generate karta hai.
class Point
attr_accessor :x, :y
def initialize(x, y)
@x = x
@y = y
end
def to_s
"(#{@x}, #{@y})"
end
end
p = Point.new(1, 2)
puts p
p.x = 10
puts p.x
puts p
(1, 2) 10 (10, 2)
p.x = 10 exactly ek public field ko assign karne jaisa dikhta hai, lekin ye actually ek method call hai (x=) jo attr_accessor ne generate kiya — Ruby ka syntax ek generated setter method ko call site par direct field access se indistinguishable bana deta hai. to_s wo method hai jise puts automatically call karta hai jab use ek object ko directly print karne ke liye kaha jaata hai, isi liye puts p (1, 2) ki tarah render hua, kisi default object description ki tarah nahi. Next: inheritance and modules — class inheritance plus Ruby ka mixin mechanism.
Practice exercise
class Point define karo attr_accessor :x, :y aur initialize(x, y) ke saath. Point.new(1, 2) create karo, p.x = 10 set karo, phir p.x aur p.y print karo.