← Back to Ruby Course | Chapter 2: Variables & Types | Lesson 7 of 7

Type Conversion कैसे करें

Type conversion एक तरह की value को दूसरी में बदलता है, जैसे text 5 को number 5 में बदलना। Ruby के पास इन बदलावों के लिए to_i और to_s जैसे methods हैं।

In this page:

  1. Type Conversion
Syntax
ruby
"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

markup
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
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. "abc".to_i इस्तेमाल करना और एक error की उम्मीद करना, जब यह silently 0 return करता है; ArgumentError raise करने के लिए Integer("abc") इस्तेमाल करें।
  2. "5" + 3 जैसे एक string और एक integer add करना, जो TypeError raise करता है जब तक आप एक side convert न करें।
  3. "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:

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.