Data Types
Type Conversion
Ruby conversion methods turn strings into numbers when input should be calculated.
conversion method
Methods such as `to_i` and `to_f` convert a value into an integer or floating-point number.
Type Conversion
conversion.rb
Replay: real traced execution (multi-file project)
raw_count = "6"
count = raw_count.to_i
double_count = count * 2
puts "count=#{count}"
puts "double=#{double_count}"
raw_count = "3"
count = raw_count.to_i
double_count = count * 2
puts "count=#{count}"
puts "double=#{double_count}"
raw_count = "10"
count = raw_count.to_i
double_count = count * 2
puts "count=#{count}"
puts "double=#{double_count}"
raw_count ← 6, count ← 6, double_count ← 12
1raw_count→ 6 = "6" #@raw_count="3", "10"2count→ 6 = raw_count.to_i63double_count→ 12 = count6 * 245puts "count=#{count6}"6puts "double=#{double_count12}"outputcount=6 double=12
raw_count ← 3, count ← 3, double_count ← 6
1raw_count→ 3 = "3"2count→ 3 = raw_count.to_i33double_count→ 6 = count3 * 245puts "count=#{count3}"6puts "double=#{double_count6}"outputcount=3 double=6
raw_count ← 10, count ← 10, double_count ← 20
1raw_count→ 10 = "10"2count→ 10 = raw_count.to_i103double_count→ 20 = count10 * 245puts "count=#{count10}"6puts "double=#{double_count20}"outputcount=10 double=20
Follow the Conversion
raw_countstarts as"6".raw_count.to_iconverts the text to integer6.double_count = count * 2becomes12.- The program prints
count=6anddouble=12. | raw_count | count | double_count | | --- | --- | --- | | "3" | 3 | 6 | | "6" | 6 | 12 | | "10" | 10 | 20 |
Exercise: conversion.rb
Reproduce count=6 and double=12, then use the pinned raw_count values 3 and 10 to predict each doubled value.