What does the to_i argument base actually do?
ruby
Solution
This argument specifies the number system the the receiver represents. In computer fields you encounter three common number systems. They are:
- Hexadecimal (base 16)
- Octal (base 8)
- Binary (base 2)
You can think of these as being the number of "characters" you cycle through before starting a new "place". For example once you go from 0 to 9 you start over at 0.
When you ask the object to convert itself to a number, it has to know what it currently represents. Once it knows this, by you specifying, it can do the math to convert the number. An example of why this is important to know is the string "10".
- In decimal "10" = 10 (decimal)
- In binary "10" = 2 (decimal)
- In hexadecimal "10" = 16 (decimal)
- In octal "10" = 8 (decimal)
Problem
What is the base argument on the `to_i` String#method actually do? Some examples: `"2".to_i(2) == 0` `"2".to_i(36) == 2` `"2".to_i(4) == 2` `"ff".to_i(36) == 555` - `"ff".to_i(16) == 255` On Binary: `"1000".to_i(2) == 8` `"1000".to_i(16) == 4096` The docs say: to_i(base=10) → integer Returns the result of interpreting leading characters in str as an integer base base (between 2 and 36). Extraneous characters past the end of a valid number are ignored. If there is not a valid number at the start of str, 0 is returned. This method never raises an exception when base is valid. However, I am still unclear by this explanation, can someone please explain. Thanks.