Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Converting string to integer or float

  • to_i
  • to_i?
  • to_f
  • to_f?
values = ["42", "42.1", "abc", "0"]
values.each { |val|
  puts val
  puts val.to_i?
  if val.to_i?
    puts "Convertable to Int32"
  end

  puts val.to_f?
  if val.to_f?
    puts "Convertable to Floar64"
  end
  puts "---"
}
42
42
Convertable to Int32
42.0
Convertable to Floar64
---
42.1

42.1
Convertable to Floar64
---
abc


---
0
0
Convertable to Int32
0.0
Convertable to Floar64
---