← Back to Ruby Course | Chapter 9: OOP | Lesson 4 of 7

attr_accessor क्या है

attr_accessor एक object पर एक value पढ़ने और बदलने के तरीके एक single line में बनाता है, एक box पर एक window और एक door लगाने की तरह। इसके बिना आप हर एक हाथ से लिखते।

In this page:

  1. attr_accessor
Syntax
ruby
class ClassName
  attr_accessor :attribute
  attr_reader :read_only
  attr_writer :write_only
end

attr_accessor

attr_accessor :name automatically एक instance variable के लिए एक getter (name) और setter (name=) method दोनों generate करता है, आपको इन्हें manually लिखने से बचाते हुए।

attr_reader सिर्फ एक getter generate करता है, और attr_writer सिर्फ एक setter generate करता है, जब आप read या write access restrict करना चाहें। यह Ruby की सबसे commonly इस्तेमाल होने वाली metaprogramming conveniences में से एक है।

Note: read-only properties के लिए attr_reader इस्तेमाल करें जिन्हें आप external code से directly modify नहीं करवाना चाहते।

उदाहरण: attr_accessor

markup
class Product
  attr_accessor :name, :price

  def initialize(name, price)
    @name = name
    @price = price
  end
end

p = Product.new("Pen", 2.5)
puts p.name
p.price = 3.0
puts p.price
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. name = "x" से एक method के अंदर assign करना और attribute बदलने की उम्मीद करना, जब यह एक local variable बनाता है; self.name = "x" इस्तेमाल करें।
  2. सिर्फ पढ़ने की ज़रूरत होने पर attr_accessor इस्तेमाल करना, जब attr_reader safer है।
  3. बिना colon के attr_accessor name लिखना, जो name नाम का एक variable ढूंढता है।
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.