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 usay 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 waqai sab se close comparison hai — lekin Python, Ruby ke bar-aks, apne ints par abhi bhi koi method-call surface nahi rakhta, to 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 ke wo abhi waqai 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 bare mein kuch bhi aisa nahi tha jis ka 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 waqai objects hain, special-cased primitives nahi. Aage: strings — interpolation, concatenation, aur common string methods.

Practice exercise

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