Keyword Arguments (**kwargs) क्या हैं
Keyword arguments आपको एक method call करते वक्त हर input को नाम से label करने देते हैं, एक order form पर 'size: large' लिखने की तरह। Order अब matter नहीं करता और पढ़ना आसान है।
In this page:
Syntax
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)
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")
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. #}
आम गलतियां
- keyword arguments positionally pass करना, जैसे
configure("server1"), जो Ruby 3 सेArgumentErrorraise करता है। name:जैसा एक required keyword भूल जाना, जोArgumentError (missing keyword: :name)raise करता है।timeot: 60जैसे एक keyword misspell करना, जोunknown keywordraise करता है।
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: