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

initialize क्या है

initialize वह setup है जो automatically चलता है जब आप एक नया object बनाते हैं, box से निकलते वक्त एक toy assemble और charge करने की तरह। यह object को इसकी पहली values देता है।

In this page:

  1. initialize
Syntax
ruby
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

markup
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
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. इसे init या Initialize नाम देना, जब यह exactly initialize होना चाहिए।
  2. गलत संख्या arguments के साथ Person.new call करना, जो ArgumentError raise करता है।
  3. instance variables से पहले @ भूल जाना, इसलिए method खत्म होने पर values खो जाती हैं।
🔒

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.