← Back to Ruby Course | Chapter 7: Methods | Lesson 5 of 7

Keyword Arguments (**kwargs) क्या हैं

Keyword arguments आपको एक method call करते वक्त हर input को नाम से label करने देते हैं, एक order form पर 'size: large' लिखने की तरह। Order अब matter नहीं करता और पढ़ना आसान है।
Syntax
ruby
def method_name(name:, option: default_value)
  # body
end

method_name(name: value, option: other_value)

def other_method(**kwargs)
  # kwargs is a hash
end

Keyword Arguments (**kwargs)

Ruby named keyword arguments support करता है, def configure(name:, timeout: 30), जो call site पर position की बजाय नाम से pass होने चाहिए, कई parameters वाले methods के लिए readability improve करते हुए।

**kwargs किसी भी संख्या में extra keyword arguments को एक hash में collect करता है, जैसे *args positional वाले collect करता है। बिना default वाले Keyword arguments required हैं और omit होने पर एक error raise करते हैं।

Note: Keyword arguments call sites को self-documenting बनाते हैं, जैसे connect(host: "localhost", port: 8080) दो positional values से clearer है।

उदाहरण: Keyword Arguments (**kwargs)

markup
def configure(name:, timeout: 30)
  puts "Name: #{name}, Timeout: #{timeout}"
end

configure(name: "server1")
configure(name: "server2", timeout: 60)

def show_options(**options)
  puts options.inspect
end

show_options(color: "red", size: "large")
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. keyword arguments positionally pass करना, जैसे configure("server1"), जो Ruby 3 से ArgumentError raise करता है।
  2. name: जैसा एक required keyword भूल जाना, जो ArgumentError (missing keyword: :name) raise करता है।
  3. timeot: 60 जैसे एक keyword misspell करना, जो unknown keyword raise करता है।
🔒

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.