attr_accessor क्या है
attr_accessor एक object पर एक value पढ़ने और बदलने के तरीके एक single line में बनाता है, एक box पर एक window और एक door लगाने की तरह। इसके बिना आप हर एक हाथ से लिखते।
In this page:
Syntax
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
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
Login to try C/C++/Java/PHP code in the editor
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. #}
आम गलतियां
name = "x"से एक method के अंदर assign करना और attribute बदलने की उम्मीद करना, जब यह एक local variable बनाता है;self.name = "x"इस्तेमाल करें।- सिर्फ पढ़ने की ज़रूरत होने पर
attr_accessorइस्तेमाल करना, जबattr_readersafer है। - बिना colon के
attr_accessor nameलिखना, जोnameनाम का एक variable ढूंढता है।
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: