Saturday, August 4, 2007

Conversions


Conversions
view image with ruby code and result

To get the string version of an object, we simply write .to_s after it
var1 = 20
var2 = '30'
puts var1.to_s + var2
puts var1 + var2.to_i
.to_s gives the String
.to_i gives the Integer
.to_f gives the Float version
let's try some more interesting (and a few just weird) conversions:
puts '30' .to_f
puts '200.7474' .to_f
puts '302.3333' .to_i
puts ''
puts '11 is my favorite number!' .to_i
puts 'who asked you about 11 or whatever?' .to_i
puts ''
puts 'me anand' .to_s
puts 5.to_i

so this probably gave you some surprises. The first one is pretty standar, giving 30.0. after that we converted the string '200.7474' to a float and to an integer

No comments: