AnyCompiler

Variables aur Types

Ek Ruby variable banana sirf ek assignment hai — x = 5. Koi let, var, my, def, ya kisi tarah ka type annotation nahi hota; kisi naam ko pehli baar assign karna hi use existence mein laata hai. Ye is site ki kisi bhi language se zyada minimal hai: Perl ko bhi sigil chahiye hota hai aur Python mein nothing-but-a-name-with-no-sigil-at-all actually sabse close comparison hai — lekin Python, Ruby ke unlike, apne ints par abhi bhi koi method-call surface nahi rakhta, toh ye similarity sirf skin deep hai.

Ruby dynamically typed hai: ek variable ka koi declared type nahi hota, sirf jo object wo abhi point kar raha hai. .class kisi bhi object se poochta hai ki wo abhi actually kya hai.

x = 5
y = 3.14
name = "Ruby"
is_fun = true
nothing = nil

puts x.class
puts y.class
puts name.class
puts is_fun.class
puts nothing.class

x = "now I'm a string"
puts x.class
Output
Integer
Float
String
TrueClass
NilClass
String

Same name x pehle ek Integer aur phir, reassignment ke baad, ek String hold karta tha — variable ke baare mein kuch bhi aisa nahi tha jiska fixed type violate ho sake. true aur false apni khud ki class ke sole instance hain (TrueClass, FalseClass), aur nil NilClass ka sole instance hai — sab genuinely objects hain, special-cased primitives nahi. Next: strings — interpolation, concatenation, aur common string methods.

Practice exercise

x = 5 set karo aur uski class print karo, phir x ko string "now a string" mein reassign karo aur uski class phir print karo.