String to number conversion in Ruby

19 Sep

When converting a string in Ruby to and in using the value’s to_i method it will do some interesting conversion.


  • ‘5’ becomes 5 — Cool
  • ‘I have 5’ becomes 0 — kind of a weird failure, 0 could be a perfectly fine conversion
  • ‘5 is five’ becomes 5 — Really odd behavior, but the conversion is done until an incorrect character is encountered.  After this the rest of the string is ignored.  So
  • ‘5 is 5’ becomes 5
  • ‘5,000’ becomes 5

Where this is helpful so far is when someone is entering text through the command prompt.  When a person enters text prompted from gets the new line added from the user pressing enter is included.  So if a user enters 5, then the gets string contains ‘5n’.  In most languages this would cause and issue, but with how ruby does it’s conversion of ‘5n’ becomes 5.

No Comments

Posted in Web/Tech