Type Conversion कैसे करें
Type conversion एक तरह की value को दूसरी में बदलता है, जैसे text 5 को number 5 में बदलना। Ruby के पास इन बदलावों के लिए to_i और to_s जैसे methods हैं।
In this page:
Syntax
"42".to_i
"3.14".to_f
42.to_s
(1..3).to_a
Type Conversion
Ruby कई types पर to_i, to_f, to_s, और to_a methods देता है इनके बीच convert करने के लिए। एक non-numeric string पर to_i एक error raise करने की बजाय 0 return करता है, जो careful न होने पर input mistakes hide कर सकता है।
Integer() और Float() (capitalized, functions की तरह इस्तेमाल होते हैं) stricter alternatives हैं जो invalid input पर एक error raise करते हैं।
Warning:
"abc".to_i silently 0 return करता है error raise करने की बजाय -- अगर आप चाहते हैं invalid input raise करे Integer("abc") इस्तेमाल करें।
उदाहरण: Type Conversion
text = "42"
converted = text.to_i
puts converted.class
puts converted + 8
puts "abc".to_i # silently becomes 0
begin
Integer("abc")
rescue ArgumentError => e
puts "Integer() raised: #{e.message}"
end
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. #}
आम गलतियां
"abc".to_iइस्तेमाल करना और एक error की उम्मीद करना, जब यह silently0return करता है;ArgumentErrorraise करने के लिएInteger("abc")इस्तेमाल करें।"5" + 3जैसे एक string और एक integer add करना, जोTypeErrorraise करता है जब तक आप एक side convert न करें।"3.9"जैसी एक decimal string परto_iइस्तेमाल करना और4की उम्मीद करना, जब यह3देता है।
चैप्टर सारांश
- Ruby में local, global, instance, और class variables हैं।
- Integer, float, boolean,
nil, और symbol values common types हैं। - Type conversion एक value को एक type से दूसरे में बदलता है।
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: