initialize क्या है
initialize वह setup है जो automatically चलता है जब आप एक नया object बनाते हैं, box से निकलते वक्त एक toy assemble और charge करने की तरह। यह object को इसकी पहली values देता है।
In this page:
Syntax
class ClassName
def initialize(param1, param2)
@attribute1 = param1
@attribute2 = param2
end
end
object = ClassName.new(value1, value2)
initialize
initialize एक special method है जो automatically चलता है जब भी एक class पर .new call होता है, एक object की initial state set up करने के लिए इस्तेमाल होता है।
इसके parameters वे arguments बन जाते हैं जो आप .new को pass करते हैं। ज़्यादातर methods के उलट, initialize implicitly call होता है और इसकी return value ignore होती है -- .new हमेशा नया object खुद return करता है।
Note:
initialize की return value हमेशा ignore होती है -- .new हमेशा newly created object return करता है, चाहे initialize कुछ भी return करे।
उदाहरण: initialize
class Person
def initialize(name, age)
@name = name
@age = age
end
def introduce
puts "I'm #{@name}, #{@age} years old"
end
end
alice = Person.new("Alice", 30)
alice.introduce
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. #}
आम गलतियां
- इसे
initयाInitializeनाम देना, जब यह exactlyinitializeहोना चाहिए। - गलत संख्या arguments के साथ
Person.newcall करना, जोArgumentErrorraise करता है। - instance variables से पहले
@भूल जाना, इसलिए method खत्म होने पर values खो जाती हैं।
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: