Ruby/Number/Convert to Integer

Материал из Wiki.crossplatform.ru

Перейти к: навигация, поиск

Содержание

ArgumentError: invalid value for Integer: "ights"

Integer("1001 nights")



convert a binary number from a string

puts Integer("0b11110010")



convert a character code

puts Integer(z)



convert a floating-point number

puts Integer(1.4)



convert a hexadecimal number

puts Integer(0x20)



convert an octal number

puts Integer(0177)



convert a string

puts Integer("256")



Converting Between Characters and Values

?a                       # => 97
?!                       # => 33
?\n                      # => 10
"a"[0]                   # => 97
"bad sound"[1]           # => 97



Converting Between Classes

puts "12" + "10"
puts 12 + 10
puts "12".to_i + "10".to_i
puts 12.to_s + 10.to_s



Convert string to integer by parameter

"1045".to_i(10)                   # => 1045
"-1001001".to_i(2)                # => -73
"abc".to_i(16)                    # => 2748
"abc".to_i(20)                    # => 4232
"number".to_i(36)                 # => 1442151747
"zz1z".to_i(36)                   # => 1678391
"abcdef".to_i(16)                 # => 11259375
"AbCdEf".to_i(16)                 # => 11259375



Convert string to number with non number string

puts "13: a baker"s dozen".to_i                          # => 13
puts "1001 Nights".to_i                                  # => 1001
puts "Night".to_i                                        
puts "Equipment".to_f
puts "$60.50".to_f                                       # => 0.0
puts "AAAA!".hex                                         
puts "0xA2Z".hex                                         # => 162
puts "-10".oct                                           # => -8
puts "-109".oct                                          # => -8
puts "3.14".to_i                                         # => 3



Number parser by regular expressons

class NumberParser
  @@number_regexps = {
    :to_i => /([+-]?[0-9]+)/,
    :to_f => /([+-]?([0-9]*\.)?[0-9]+(e[+-]?[0-9]+)?)/i,
    :oct => /([+-]?[0-7]+)/,
    :hex => /\b([+-]?(0x)?[0-9a-f]+)\b/i
  }
  def NumberParser.re(parsing_method=:to_i)
    re = @@number_regexps[parsing_method]
    raise ArgumentError, "No regexp for #{parsing_method.inspect}!" unless re
    return re
  end
  def extract(s, parsing_method=:to_i)
    numbers = []
    s.scan(NumberParser.re(parsing_method)) do |match|
      numbers << match[0].send(parsing_method)
    end
    numbers
  end
end
p = NumberParser.new
pw = "104 and 391."
NumberParser.re(:to_i).match(pw).captures     
p.extract(pw, :to_i)                          
p.extract("$60.50", :to_f)                    
p.extract("AAA", :hex)
p.extract("017.", :oct)          
p.extract("From 0 to 10e60 AA -2.4 s")



Parsing A Number From A String

"400".to_i                      # => 400



to_i gives the integer version of an object, and to_f gives the float version

var1 = 2
var2 = "5"
puts var1.to_s + var2
puts var1 + var2.to_i