## 2.24. Converting Strings to Numbers (Decimal and Otherwise)Basically there are two ways to convert strings to numbers: the The simple case is trivial, and these are equivalent: x = "123".to_i # 123 y = Integer("123") # 123 When a string is not a valid number, however, their behaviors differ: x = "junk".to_i # silently returns 0 y = Integer("junk") # error
x = "123junk".to_i # 123 y = Integer("123junk") # error Both allow leading and trailing whitespace: x = " 123 ".to_i # 123 y = Integer(" 123 ") # 123 Floating point conversion works much the same way: x = "3.1416".to_f # 3.1416 y = Float("2.718") # 2.718 Both conversion methods honor scientific notation: x = Float("6.02e23") # 6.02e23 y = "2.9979246e5".to_f # 299792.46
When talking about converting between numeric bases, strings always are involved. After all, an integer is an integer, and they are all stored in binary. Base conversion, therefore, always means converting to or from some kind of string. Here we're looking at converting from a string. (For the reverse, see section 5.18 "Performing Base Conversions" and section 5.5 "Formatting Numbers for Output.") When a number appears in program text as a literal numeric constant, it may have a "tag" in front of it to indicate base. These tags are These tags are honored by the x = Integer("0b111") # binary - returns 7 y = Integer("0111") # octal - returns 73 z = Integer("0x111") # hexadecimal - returns 291 x = "0b111".to_i # 0 y = "0111".to_i # 0 z = "0x111".to_i # 0
x = "111".to_i(2) # 7 y = "111".to_i(8) # octal - returns 73 z = "111".to_i(16) # hexadecimal - returns 291 x = "0b111".to_i # 0 y = "0111".to_i # 0 z = "0x111".to_i # 0 Because of the "standard" behavior of these methods, a digit that is inappropriate for the given base will be treated differently: x = "12389".to_i(8) # 123 (8 is ignored) y = Integer("012389") # error (8 is illegal) Although it might be of limited usefulness, x = "123".to_i(5) # 66 y = "ruby".to_i(36) # 1299022 It's also possible to use the str = "234 234 234" x, y, z = str.scanf("%d %o %x") # 234, 156, 564 The |

The Ruby Way, Second Edition: Solutions and Techniques in Ruby Programming (2nd Edition)

ISBN: 0672328844

EAN: 2147483647

EAN: 2147483647

Year: 2004

Pages: 269

Pages: 269

Authors: Hal Fulton

Similar book on Amazon

flylib.com © 2008-2017.

If you may any questions please contact us: flylib@qtcs.net

If you may any questions please contact us: flylib@qtcs.net